From 4f4758f7fec6d6f4d4c26c575c718748ccc79c68 Mon Sep 17 00:00:00 2001 From: David Ashby Date: Wed, 28 Jul 2021 21:06:49 -0400 Subject: [PATCH] fix a panic and handle cleaning up after a panic --- cmd/manage/main.go | 14 ++++++++++++++ config/config.go | 1 + ui/ui.go | 3 +++ 3 files changed, 18 insertions(+) diff --git a/cmd/manage/main.go b/cmd/manage/main.go index 92a3edb..5d9d5fe 100644 --- a/cmd/manage/main.go +++ b/cmd/manage/main.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "os" + "runtime/debug" "sync" "git.yetaga.in/alazyreader/library/book" @@ -116,6 +117,19 @@ func main() { if err != nil { log.Fatalln(err) } + // cleanup our screen and log if we panic and crash out somewhere + defer func() { + if r := recover(); r != nil { + if screen != nil { + screen.Fini() + } + fmt.Println("fatal panic;", r) + if c.Debug { + fmt.Println("stacktrace: \n" + string(debug.Stack())) + } + return + } + }() l := ui.NewList(Titles(state.Get("library").([]book.Book)), 0) menu := ui.NewBox( diff --git a/config/config.go b/config/config.go index 08bbab1..0813444 100644 --- a/config/config.go +++ b/config/config.go @@ -6,4 +6,5 @@ type Config struct { DBHost string DBPort string DBName string + Debug bool } diff --git a/ui/ui.go b/ui/ui.go index b7d12b6..a32d002 100644 --- a/ui/ui.go +++ b/ui/ui.go @@ -296,6 +296,9 @@ func (l *List) Selected() int { } func (l *List) SelectedID() int { + if l.listItems == nil || len(l.listItems) == 0 { + return 0 + } return l.listItems[l.selected].Key }