Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

status: support wrapped errors in FromContextError #4977

Merged
merged 1 commit into from
Nov 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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