Skip to content

Commit 218b4cc

Browse files
committed
Map status code only when grpc/codes.Code has not been set
1 parent 3436f0f commit 218b4cc

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

handlers.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,9 @@ func WithStatusCodeMap(m map[int]codes.Code) interface {
100100
} {
101101
return WithAppErrorHandler(func(c context.Context, err *apperrors.Error) error {
102102
newCode := codes.Unknown
103-
if c, ok := m[err.StatusCode]; ok {
103+
if s, ok := status.FromError(err.Err); ok {
104+
newCode = s.Code()
105+
} else if c, ok := m[err.StatusCode]; ok {
104106
newCode = c
105107
}
106108
return status.Error(newCode, err.Error())

interceptors_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,14 @@ func (s *errorWithStatusService) EmptyCall(context.Context, *errorstesting.Empty
5252
return nil, apperrors.WithStatusCode(errors.New("This error has a status code"), s.Code)
5353
}
5454

55+
type errorWithGrpcStatusService struct {
56+
Code codes.Code
57+
}
58+
59+
func (s *errorWithGrpcStatusService) EmptyCall(context.Context, *errorstesting.Empty) (*errorstesting.Empty, error) {
60+
return nil, apperrors.Wrap(status.Error(s.Code, "This error has a gRPC status code"))
61+
}
62+
5563
// Testings
5664
// ================================================
5765
func Test_UnaryServerInterceptor_WhenDoesNotRespondErrors(t *testing.T) {
@@ -279,6 +287,38 @@ func Test_UnaryServerInterceptor_WithStatusCodeMap_WhenUnknownCode(t *testing.T)
279287
}
280288
}
281289

290+
func Test_UnaryServerInterceptor_WithStatusCodeMap_WhenAlreadySet(t *testing.T) {
291+
code := codes.Unauthenticated
292+
293+
ctx := errorstesting.CreateTestContext(t)
294+
ctx.Service = &errorWithGrpcStatusService{Code: code}
295+
ctx.AddUnaryServerInterceptor(
296+
UnaryServerInterceptor(
297+
WithStatusCodeMap(map[int]codes.Code{
298+
int(code): codes.Aborted,
299+
}),
300+
),
301+
)
302+
ctx.Setup()
303+
defer ctx.Teardown()
304+
305+
resp, err := ctx.Client.EmptyCall(context.Background(), &errorstesting.Empty{})
306+
307+
if resp != nil {
308+
t.Error("The request should not return any responses")
309+
}
310+
311+
if err == nil {
312+
t.Error("The request should return an error")
313+
}
314+
315+
if st, ok := status.FromError(err); !ok {
316+
t.Error("Returned error should has status code")
317+
} else if got, want := st.Code(), code; got != want {
318+
t.Errorf("Returned error had status code %v, want %v", got, want)
319+
}
320+
}
321+
282322
func Test_UnaryServerInterceptor_WithStatusCodeMapper(t *testing.T) {
283323
code := 50
284324
mappedCode := codes.Unavailable

0 commit comments

Comments
 (0)