Skip to content

Commit

Permalink
Support wrapped errors in status.FromContextError
Browse files Browse the repository at this point in the history
Return an appropriate Status from status.FromContext error if either the supplied error or an error in its chain is one of the context sentinel error values.
  • Loading branch information
bestbeforetoday committed Nov 12, 2021
1 parent 82d8af8 commit 2a93c56
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 2a93c56

Please sign in to comment.