Skip to content

Commit

Permalink
fix(grpc): add stacktrace to locate panic (#1333)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ja7ad authored Jun 10, 2024
1 parent 8a73a3e commit 9088254
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 5 deletions.
11 changes: 8 additions & 3 deletions www/grpc/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package grpc

import (
"context"
"log"
"runtime/debug"

rec "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
"github.com/pactus-project/pactus/util/htpasswd"
Expand All @@ -28,10 +28,15 @@ func BasicAuth(storedCredential string) grpc.UnaryServerInterceptor {
}
}

func Recovery() grpc.UnaryServerInterceptor {
func (s *Server) Recovery() grpc.UnaryServerInterceptor {
recovery := func(p any) (err error) {
err = status.Errorf(codes.Unknown, "%v", p)
log.Println("recovery: panic triggered in grpc server", "error", err)
stackTrace := debug.Stack()
s.logger.Error(
"recovery panic triggered in grpc server",
"error", err,
"stacktrace", string(stackTrace),
)

return err
}
Expand Down
4 changes: 3 additions & 1 deletion www/grpc/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ func TestBasicAuth(t *testing.T) {
}

func TestGrpcRecovery(t *testing.T) {
interceptor := Recovery()
s := setup(t, nil)

interceptor := s.server.Recovery()

_, err := interceptor(context.Background(), nil, &grpc.UnaryServerInfo{}, mockUnaryPanicHandler)
if status.Code(err) != codes.Unknown {
Expand Down
2 changes: 1 addition & 1 deletion www/grpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func (s *Server) startListening(listener net.Listener) error {
opts = append(opts, BasicAuth(s.config.BasicAuth))
}

opts = append(opts, Recovery())
opts = append(opts, s.Recovery())

grpcServer := grpc.NewServer(grpc.ChainUnaryInterceptor(opts...))

Expand Down

0 comments on commit 9088254

Please sign in to comment.