Skip to content

Commit

Permalink
Add basic defer-recover panic handler (#53)
Browse files Browse the repository at this point in the history
* Add defer-recover panic handler

* Add changelog
  • Loading branch information
bradleyjkemp authored Aug 26, 2019
1 parent 4c9ac20 commit e11527e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Changelog

## v0.2.3 (Unreleased)
* Added a defer-recover handler so that any panics in the `grpc-proxy` interceptor do not kill the proxy [#53](https://github.com/bradleyjkemp/grpc-tools/pull/53).

## [v0.2.2](https://github.com/bradleyjkemp/grpc-tools/releases/tag/v0.2.2)
* Improved behaviour and logging when a message fails to be decoded [#51](https://github.com/bradleyjkemp/grpc-tools/pull/51).

Expand Down
17 changes: 16 additions & 1 deletion grpc-proxy/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import (
"flag"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"runtime/debug"
)

type Configurator func(*server)
Expand All @@ -16,7 +19,19 @@ func WithOptions(options ...grpc.ServerOption) Configurator {

func WithInterceptor(interceptor grpc.StreamServerInterceptor) Configurator {
return func(s *server) {
s.serverOptions = append(s.serverOptions, grpc.StreamInterceptor(interceptor))
s.serverOptions = append(s.serverOptions, grpc.StreamInterceptor(recoverWrapper(s, interceptor)))
}
}

func recoverWrapper(s *server, interceptor grpc.StreamServerInterceptor) grpc.StreamServerInterceptor {
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
defer func() {
if r := recover(); r != nil {
err = status.Errorf(codes.Internal, "proxy error: %v", r)
s.logger.WithError(err).Warn("panic in StreamHandler: ", string(debug.Stack()))
}
}()
return interceptor(srv, ss, info, handler)
}
}

Expand Down

0 comments on commit e11527e

Please sign in to comment.