From 08c5779009125896fb23317c9727cb53d3124eb4 Mon Sep 17 00:00:00 2001 From: Aleksandr Razumov Date: Tue, 14 Nov 2023 01:28:27 +0300 Subject: [PATCH] fix: correctly recover panic --- app/app.go | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/app/app.go b/app/app.go index a5882ce..6fd4926 100644 --- a/app/app.go +++ b/app/app.go @@ -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. @@ -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)