go-zero/zrpc/internal/serverinterceptors/crashinterceptor.go

43 lines
1.1 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package serverinterceptors
import (
"context"
"runtime/debug"
"github.com/zeromicro/go-zero/core/logx"
2020-07-26 17:09:05 +08:00
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
2021-03-01 23:52:44 +08:00
// StreamCrashInterceptor catches panics in processing stream requests and recovers.
2020-07-26 17:09:05 +08:00
func StreamCrashInterceptor(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)
}
2021-03-01 23:52:44 +08:00
// UnaryCrashInterceptor catches panics in processing unary requests and recovers.
func UnaryCrashInterceptor(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)
2020-07-26 17:09:05 +08:00
}
func handleCrash(handler func(interface{})) {
if r := recover(); r != nil {
handler(r)
}
}
func toPanicError(r interface{}) error {
2021-08-15 15:33:45 +08:00
logx.Errorf("%+v\n\n%s", r, debug.Stack())
2020-07-26 17:09:05 +08:00
return status.Errorf(codes.Internal, "panic: %v", r)
}