From 064fe2c7a6411dd1550d2476b92ee29468edbf9d Mon Sep 17 00:00:00 2001 From: Helmut Merz Date: Tue, 8 Aug 2023 14:57:34 +0200 Subject: [PATCH] provide Recover() (ex LogCatch) function, use in core.Step() --- core/core.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/core/core.go b/core/core.go index a3199ae..96ef5ac 100644 --- a/core/core.go +++ b/core/core.go @@ -1,6 +1,8 @@ package core import ( + "fmt" + lib "git.sr.ht/~cco/go-scopes" "git.sr.ht/~cco/go-scopes/config" "git.sr.ht/~cco/go-scopes/core/action" @@ -22,7 +24,7 @@ func Listen(ctx lib.Context) { func Step(ctx lib.Context) (loop bool) { loop = true - //defer ctx.LogCatch("Step") + defer Recover(ctx, "core.Step") select { case msg := <-ctx.Mailbox(): loop = lib.HandleMsg(ctx, msg) @@ -45,6 +47,20 @@ func HandleDone(ctx lib.Context) bool { return false } +// Recover checks if there was a panic condition and recovers from it. +// In this case the error is logged and returned. +// Returns the error (or nil if there wasn't any). +func Recover(ctx lib.Context, txt string) interface{} { + err := recover() + if err != nil { + if estr, ok := err.(string); ok { + err = fmt.Errorf(estr) + } + logging.Error(ctx, err.(error)).Msg(txt) + } + return err +} + func init() { config.DefaultStart = Start // avoid import cycle config.DefaultStep = Step