You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.1 KiB
Go
43 lines
1.1 KiB
Go
4 years ago
|
package serverinterceptors
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"runtime/debug"
|
||
|
|
||
3 years ago
|
"github.com/zeromicro/go-zero/core/logx"
|
||
4 years ago
|
"google.golang.org/grpc"
|
||
|
"google.golang.org/grpc/codes"
|
||
|
"google.golang.org/grpc/status"
|
||
|
)
|
||
|
|
||
2 years ago
|
// StreamRecoverInterceptor catches panics in processing stream requests and recovers.
|
||
|
func StreamRecoverInterceptor(svr interface{}, stream grpc.ServerStream, _ *grpc.StreamServerInfo,
|
||
4 years ago
|
handler grpc.StreamHandler) (err error) {
|
||
|
defer handleCrash(func(r interface{}) {
|
||
|
err = toPanicError(r)
|
||
|
})
|
||
|
|
||
3 years ago
|
return handler(svr, stream)
|
||
4 years ago
|
}
|
||
|
|
||
2 years ago
|
// UnaryRecoverInterceptor catches panics in processing unary requests and recovers.
|
||
|
func UnaryRecoverInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo,
|
||
3 years ago
|
handler grpc.UnaryHandler) (resp interface{}, err error) {
|
||
|
defer handleCrash(func(r interface{}) {
|
||
|
err = toPanicError(r)
|
||
|
})
|
||
|
|
||
|
return handler(ctx, req)
|
||
4 years ago
|
}
|
||
|
|
||
|
func handleCrash(handler func(interface{})) {
|
||
|
if r := recover(); r != nil {
|
||
|
handler(r)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func toPanicError(r interface{}) error {
|
||
3 years ago
|
logx.Errorf("%+v\n\n%s", r, debug.Stack())
|
||
4 years ago
|
return status.Errorf(codes.Internal, "panic: %v", r)
|
||
|
}
|