Skip to content

Commit

Permalink
context: added panic recovery to forked contexts
Browse files Browse the repository at this point in the history
  • Loading branch information
Mario Jorge Silveira Pereira committed Nov 16, 2023
1 parent dee9e49 commit 4c4143e
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/middleware/request/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package request

import (
"context"
"fmt"
"time"

"github.com/cuvva/cuvva-public-go/lib/clog"
Expand Down Expand Up @@ -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() {
Expand All @@ -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() {
Expand Down

0 comments on commit 4c4143e

Please sign in to comment.