-
Notifications
You must be signed in to change notification settings - Fork 0
/
panic_recovery.go
53 lines (46 loc) · 1.32 KB
/
panic_recovery.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package cucumber
import (
"context"
"net"
"net/http"
"os"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// PanicRecovery returns a middleware that recovers from any panics and serves error response
func PanicRecovery() HandlerFunc {
return func(c *Context) {
defer func() {
if err := recover(); err != nil {
var brokenPipe bool
if ne, ok := err.(*net.OpError); ok {
if se, ok := ne.Err.(*os.SyscallError); ok {
if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
brokenPipe = true
}
}
}
if brokenPipe {
c.Error(err.(error))
c.Abort()
} else {
c.ServeError(http.StatusInternalServerError, err.(error))
}
}
}()
c.Next()
}
}
// NewUnaryPanicRecovery creates interceptor to protect a process from aborting by panic and return Internal error as status code
func NewUnaryPanicRecovery(opts Options) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
defer func() {
if r := recover(); r != nil {
err = status.Errorf(codes.Internal, "panic: %v", r)
}
}()
return handler(ctx, req)
}
}