-
Notifications
You must be signed in to change notification settings - Fork 1
/
recovery.go
59 lines (46 loc) · 1.49 KB
/
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
54
55
56
57
58
59
package recovery
import (
"context"
"fmt"
"github.com/boxgo/box/pkg/errcode"
"github.com/boxgo/box/pkg/logger"
"github.com/boxgo/box/pkg/metric"
"google.golang.org/grpc"
)
var (
panicCounter = metric.NewCounterVec(
"grpc_server_panic_total",
"grpc server panic counter",
[]string{"method", "panic"},
)
)
func UnaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
panicked := true
defer func() {
if panicErr := recover(); panicErr != nil || panicked {
logger.Errorw("grpc unary server panic:", "panicked", panicked, "panic", panicErr)
err = errcode.ErrGRPCServerPanic.Build(panicErr)
panicCounter.WithLabelValues(info.FullMethod, fmt.Sprintf("%s", panicErr)).Inc()
}
}()
resp, err = handler(ctx, req)
panicked = false
return resp, err
}
}
func StreamServerInterceptor() grpc.StreamServerInterceptor {
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
panicked := true
defer func() {
if panicErr := recover(); panicErr != nil || panicked {
logger.Errorw("grpc stream server panic:", "panicked", panicked, "panic", panicErr)
err = errcode.ErrGRPCServerPanic.Build(panicErr)
panicCounter.WithLabelValues(info.FullMethod, fmt.Sprintf("%s", panicErr)).Inc()
}
}()
err = handler(srv, stream)
panicked = false
return err
}
}