Skip to content

Commit

Permalink
feat: allow passing a custom panic handler
Browse files Browse the repository at this point in the history
Use `WithPanicHandler()` to pass a function that gets executed on panics
  • Loading branch information
aymanbagabas committed Feb 4, 2022
1 parent 9a06319 commit 9cd5d48
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
8 changes: 8 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,11 @@ func WithANSICompressor() ProgramOption {
p.startupOptions |= withANSICompressor
}
}

// WithPanicHandler sets the program's panic handler. This won't have any effect
// if the WithoutCatchPanics option was enabled.
func WithPanicHandler(f func(*Program)) ProgramOption {
return func(p *Program) {
p.panicHandler = f
}
}
23 changes: 15 additions & 8 deletions tea.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ type Program struct {
// is on by default.
CatchPanics bool

panicHandler func(*Program)

console console.Console

// Stores the original reference to stdin for cases where input is not a
Expand Down Expand Up @@ -248,6 +250,7 @@ func NewProgram(model Model, opts ...ProgramOption) *Program {
input: os.Stdin,
msgs: make(chan Msg),
CatchPanics: true,
panicHandler: defaultPanicHandler(),
}

// Apply all options to the program.
Expand Down Expand Up @@ -349,14 +352,7 @@ func (p *Program) StartReturningModel() (Model, error) {
}()

if p.CatchPanics {
defer func() {
if r := recover(); r != nil {
p.shutdown(true)
fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r)
debug.PrintStack()
return
}
}()
defer p.panicHandler(p)
}

// Check if output is a TTY before entering raw mode, hiding the cursor and
Expand Down Expand Up @@ -671,3 +667,14 @@ func (p *Program) DisableMouseAllMotion() {
defer p.mtx.Unlock()
fmt.Fprintf(p.output, te.CSI+te.DisableMouseAllMotionSeq)
}

func defaultPanicHandler() func(*Program) {
return func(p *Program) {
if r := recover(); r != nil {
p.shutdown(true)
fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r)
debug.PrintStack()
return
}
}
}

0 comments on commit 9cd5d48

Please sign in to comment.