Files
go-zero/zrpc/internal/serverinterceptors/recoverinterceptor.go

43 lines
1.1 KiB
Go
Raw Permalink Normal View History

2020-07-26 17:09:05 +08:00
package serverinterceptors
import (
"context"
"runtime/debug"
"github.com/zeromicro/go-zero/core/logc"
2020-07-26 17:09:05 +08:00
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// StreamRecoverInterceptor catches panics in processing stream requests and recovers.
func StreamRecoverInterceptor(svr any, stream grpc.ServerStream, _ *grpc.StreamServerInfo,
2020-07-26 17:09:05 +08:00
handler grpc.StreamHandler) (err error) {
defer handleCrash(func(r any) {
err = toPanicError(context.Background(), r)
2020-07-26 17:09:05 +08:00
})
return handler(svr, stream)
2020-07-26 17:09:05 +08:00
}
// UnaryRecoverInterceptor catches panics in processing unary requests and recovers.
func UnaryRecoverInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (resp any, err error) {
defer handleCrash(func(r any) {
err = toPanicError(ctx, r)
})
return handler(ctx, req)
2020-07-26 17:09:05 +08:00
}
func handleCrash(handler func(any)) {
2020-07-26 17:09:05 +08:00
if r := recover(); r != nil {
handler(r)
}
}
func toPanicError(ctx context.Context, r any) error {
logc.Errorf(ctx, "%+v\n\n%s", r, debug.Stack())
2020-07-26 17:09:05 +08:00
return status.Errorf(codes.Internal, "panic: %v", r)
}