Skip to content

Commit

Permalink
fix: correctly recover panic
Browse files Browse the repository at this point in the history
  • Loading branch information
ernado committed Nov 13, 2023
1 parent ece9d72 commit 08c5779
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,18 @@ func Run(f func(ctx context.Context, lg *zap.Logger, m *Metrics) error, op ...Op
}

g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
g.Go(func() (rerr error) {
defer lg.Info("Shutting down")
defer func() {
// Recovering panic to allow telemetry to flush.
if ec := recover(); ec != nil {
lg.Error("Panic",
zap.String("panic", fmt.Sprintf("%v", ec)),
zap.StackSkip("stack", 1),
)
rerr = fmt.Errorf("shutting down (panic): %v", ec)
}
}()
if err := f(ctx, lg, m); err != nil {
if errors.Is(err, ctx.Err()) {
// Parent context got cancelled, error is expected.
Expand Down Expand Up @@ -132,15 +142,6 @@ func Run(f func(ctx context.Context, lg *zap.Logger, m *Metrics) error, op ...Op
os.Exit(exitCodeWatchdog)
}()

defer func() {
if ec := recover(); ec != nil {
lg.Error("Panic",
zap.String("panic", fmt.Sprintf("%v", ec)),
)
os.Exit(exitCodeApplicationErr)
}
}()

if err := g.Wait(); err != nil {
lg.Error("Failed", zap.Error(err))
os.Exit(exitCodeApplicationErr)
Expand Down

0 comments on commit 08c5779

Please sign in to comment.