/
interceptors.go
executable file
·82 lines (71 loc) · 2.38 KB
/
interceptors.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright 2017 David Ackroyd. All Rights Reserved.
// See LICENSE for licensing terms.
/*
* Copyright (c) 2018, https://github.com/airwide-code/airwide.datacenter
* All rights reserved.
*
*
*
*/
// helper recovery, RecoveryHandlerFunc spit UnaryRecoveryHandlerFunc and StreamRecoveryHandlerFunc
//
package grpc_recovery2
import (
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// RecoveryHandlerFunc is a function that recovers from the panic `p` by returning an `error`.
type UnaryRecoveryHandlerFunc func(ctx context.Context, p interface{}) (err error)
type StreamRecoveryHandlerFunc func(stream grpc.ServerStream, p interface{}) (err error)
// UnaryServerInterceptor returns a new unary server interceptor for panic recovery.
func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor {
o := evaluateOptions(opts)
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
defer func() {
if r := recover(); r != nil {
err = unaryRecoverFrom(ctx, r, o.unaryRecoveryHandlerFunc)
}
}()
// TODO(@benqi): 加一层
r, err2 := handler(ctx, req)
if err2 != nil {
err = unaryRecoverFrom(ctx, err2, o.unaryRecoveryHandlerFunc2)
return r, err
} else {
return r, nil
}
}
}
// StreamServerInterceptor returns a new streaming server interceptor for panic recovery.
func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor {
o := evaluateOptions(opts)
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
defer func() {
if r := recover(); r != nil {
err = streamRecoverFrom(stream, r, o.streamRecoveryHandlerFunc)
}
}()
return handler(srv, stream)
}
}
func unaryRecoverFrom(ctx context.Context, p interface{}, f UnaryRecoveryHandlerFunc) error {
if f == nil {
return status.Errorf(codes.Internal, "%s", p)
}
return f(ctx, p)
}
//func unaryRecoverFrom2(ctx context.Context, p interface{}, f UnaryRecoveryHandlerFunc) error {
// if f == nil {
// return status.Errorf(codes.Internal, "%s", p)
// }
// return f(ctx, p)
//}
//
func streamRecoverFrom(stream grpc.ServerStream, p interface{}, f StreamRecoveryHandlerFunc) error {
if f == nil {
return status.Errorf(codes.Internal, "%s", p)
}
return f(stream, p)
}