-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhandler.go
48 lines (37 loc) · 1.14 KB
/
handler.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
package panichandler
import (
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
var _ grpc.UnaryServerInterceptor = UnaryPanicHandler
var _ grpc.StreamServerInterceptor = StreamPanicHandler
func toPanicError(r interface{}) error {
return grpc.Errorf(codes.Internal, "panic: %v", r)
}
func UnaryPanicHandler(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
defer handleCrash(func(r interface{}) {
err = toPanicError(r)
})
return handler(ctx, req)
}
func StreamPanicHandler(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
defer handleCrash(func(r interface{}) {
err = toPanicError(r)
})
return handler(srv, stream)
}
var additionalHandlers []func(interface{})
func InstallPanicHandler(handler func(interface{})) {
additionalHandlers = append(additionalHandlers, handler)
}
func handleCrash(handler func(interface{})) {
if r := recover(); r != nil {
handler(r)
if additionalHandlers != nil {
for _, fn := range additionalHandlers {
fn(r)
}
}
}
}