|
| 1 | +package interceptors |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + stdlog "log" |
| 6 | + "runtime/debug" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/getsentry/sentry-go" |
| 10 | + grpcrecovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery" |
| 11 | + "google.golang.org/grpc" |
| 12 | + "google.golang.org/grpc/codes" |
| 13 | + "google.golang.org/grpc/status" |
| 14 | + |
| 15 | + sdkloggercontext "github.com/scribd/go-sdk/pkg/context/logger" |
| 16 | +) |
| 17 | + |
| 18 | +// RecoveryUnaryServerInterceptor returns a unary server interceptor that recovers from panics, |
| 19 | +// sends a sentry event, log in fatal level and halts the service. |
| 20 | +// IMPORTANT: This interceptor should be the last one in the interceptor chain. |
| 21 | +func RecoveryUnaryServerInterceptor() grpc.UnaryServerInterceptor { |
| 22 | + return grpcrecovery.UnaryServerInterceptor(recoveryOption...) |
| 23 | +} |
| 24 | + |
| 25 | +// RecoveryStreamServerInterceptor returns a streaming server interceptor that recovers from panics, |
| 26 | +// sends a sentry event, log in fatal level and halts the service. |
| 27 | +// IMPORTANT: This interceptor should be the last one in the interceptor chain. |
| 28 | +func RecoveryStreamServerInterceptor() grpc.StreamServerInterceptor { |
| 29 | + return grpcrecovery.StreamServerInterceptor(recoveryOption...) |
| 30 | +} |
| 31 | + |
| 32 | +var recoveryOption = []grpcrecovery.Option{ |
| 33 | + grpcrecovery.WithRecoveryHandlerContext(func(ctx context.Context, rec interface{}) (err error) { |
| 34 | + sentry.CurrentHub().Recover(rec) |
| 35 | + sentry.Flush(time.Second * 5) |
| 36 | + |
| 37 | + l, err := sdkloggercontext.Extract(ctx) |
| 38 | + if err != nil { |
| 39 | + debug.PrintStack() |
| 40 | + stdlog.Printf("logger not found in context: %v\n", err) |
| 41 | + stdlog.Fatalf("grpc: panic error: %v", rec) |
| 42 | + } |
| 43 | + |
| 44 | + l.Fatalf("panic error: %v", rec) |
| 45 | + return status.Errorf(codes.Internal, "") |
| 46 | + }), |
| 47 | +} |
0 commit comments