Skip to content

Commit

Permalink
status: support wrapped errors in FromContextError (#4977)
Browse files Browse the repository at this point in the history
  • Loading branch information
bestbeforetoday authored Nov 19, 2021
1 parent f45e617 commit d542bfc
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
19 changes: 10 additions & 9 deletions status/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ package status

import (
"context"
"errors"
"fmt"

spb "google.golang.org/genproto/googleapis/rpc/status"
Expand Down Expand Up @@ -117,18 +118,18 @@ func Code(err error) codes.Code {
return codes.Unknown
}

// FromContextError converts a context error into a Status. It returns a
// Status with codes.OK if err is nil, or a Status with codes.Unknown if err is
// non-nil and not a context error.
// FromContextError converts a context error or wrapped context error into a
// Status. It returns a Status with codes.OK if err is nil, or a Status with
// codes.Unknown if err is non-nil and not a context error.
func FromContextError(err error) *Status {
switch err {
case nil:
if err == nil {
return nil
case context.DeadlineExceeded:
}
if errors.Is(err, context.DeadlineExceeded) {
return New(codes.DeadlineExceeded, err.Error())
case context.Canceled:
}
if errors.Is(err, context.Canceled) {
return New(codes.Canceled, err.Error())
default:
return New(codes.Unknown, err.Error())
}
return New(codes.Unknown, err.Error())
}
2 changes: 2 additions & 0 deletions status/status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,8 @@ func (s) TestFromContextError(t *testing.T) {
{in: context.DeadlineExceeded, want: New(codes.DeadlineExceeded, context.DeadlineExceeded.Error())},
{in: context.Canceled, want: New(codes.Canceled, context.Canceled.Error())},
{in: errors.New("other"), want: New(codes.Unknown, "other")},
{in: fmt.Errorf("wrapped: %w", context.DeadlineExceeded), want: New(codes.DeadlineExceeded, "wrapped: "+context.DeadlineExceeded.Error())},
{in: fmt.Errorf("wrapped: %w", context.Canceled), want: New(codes.Canceled, "wrapped: "+context.Canceled.Error())},
}
for _, tc := range testCases {
got := FromContextError(tc.in)
Expand Down

0 comments on commit d542bfc

Please sign in to comment.