diff --git a/lib/middleware/request/context.go b/lib/middleware/request/context.go index c44badc..de9ac49 100644 --- a/lib/middleware/request/context.go +++ b/lib/middleware/request/context.go @@ -2,6 +2,7 @@ package request import ( "context" + "fmt" "time" "github.com/cuvva/cuvva-public-go/lib/clog" @@ -39,6 +40,14 @@ type ContextKey string // ForkContext provides a callback function with a new context inheriting values from the request context, and will log any error returned by the callback func ForkContext(ctx context.Context, fn func(context.Context) error) { + defer func() { + if r := recover(); r != nil { + err := fmt.Errorf("recovered from panic: %v", r) + if err != nil { + panic(r) + } + } + }() newCtx := cloneContext(ctx) go func() { @@ -51,6 +60,15 @@ func ForkContext(ctx context.Context, fn func(context.Context) error) { // ForkContextWithTimeout provides a callback function with a new context inheriting values from the request context with a timeout, and will log any error returned by the callback func ForkContextWithTimeout(ctx context.Context, timeout time.Duration, fn func(context.Context) error) { + defer func() { + if r := recover(); r != nil { + err := fmt.Errorf("recovered from panic: %v", r) + if err != nil { + panic(r) + } + } + }() + newCtx, cancel := context.WithTimeout(cloneContext(ctx), timeout) go func() {