Skip to content

Commit af5de0a

Browse files
author
bandl
committed
refactor(contrib/rpc/grpcx): optimize server unary interceptor error handling
1 parent 50fb349 commit af5de0a

1 file changed

Lines changed: 13 additions & 5 deletions

File tree

‎contrib/rpc/grpcx/grpcx_interceptor_server.go‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,21 @@ func (s modServer) UnaryError(
4343
ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,
4444
) (any, error) {
4545
res, err := handler(ctx, req)
46-
if err != nil {
46+
if err == nil {
47+
return res, nil
48+
}
49+
switch {
50+
// Case 1: Error already implements GRPCStatus, it's already a gRPC standard error
51+
case err.(interface{ GRPCStatus() *status.Status }) != nil:
52+
return res, err
53+
// Case 2: Error contains a valid custom error code, convert to gRPC status error
54+
case gerror.Code(err).Code() != -1:
4755
code := gerror.Code(err)
48-
if code.Code() != -1 {
49-
err = status.Error(codes.Code(code.Code()), err.Error())
50-
}
56+
return res, status.Error(codes.Code(code.Code()), err.Error())
57+
// Case 3: Invalid error code or other cases, keep the original error
58+
default:
59+
return res, err
5160
}
52-
return res, err
5361
}
5462

5563
// UnaryRecover is the first interceptor that keep server not down from panics.

0 commit comments

Comments
 (0)