Skip to content

Commit

Permalink
status: handle wrapped errors
Browse files Browse the repository at this point in the history
  • Loading branch information
psyhatter committed Mar 4, 2023
1 parent b46bdef commit 870f983
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 9 deletions.
13 changes: 4 additions & 9 deletions status/status.go
Expand Up @@ -88,9 +88,8 @@ func FromError(err error) (s *Status, ok bool) {
if err == nil {
return nil, true
}
if se, ok := err.(interface {
GRPCStatus() *Status
}); ok {
var se interface{ GRPCStatus() *Status }
if errors.As(err, &se) {
return se.GRPCStatus(), true
}
return New(codes.Unknown, err.Error()), false
Expand All @@ -110,12 +109,8 @@ func Code(err error) codes.Code {
if err == nil {
return codes.OK
}
if se, ok := err.(interface {
GRPCStatus() *Status
}); ok {
return se.GRPCStatus().Code()
}
return codes.Unknown

return Convert(err).Code()
}

// FromContextError converts a context error or wrapped context error into a
Expand Down
32 changes: 32 additions & 0 deletions status/status_test.go
Expand Up @@ -32,6 +32,7 @@ import (
cpb "google.golang.org/genproto/googleapis/rpc/code"
epb "google.golang.org/genproto/googleapis/rpc/errdetails"
spb "google.golang.org/genproto/googleapis/rpc/status"

"google.golang.org/grpc/codes"
"google.golang.org/grpc/internal/grpctest"
"google.golang.org/grpc/internal/status"
Expand Down Expand Up @@ -144,6 +145,37 @@ func (s) TestFromErrorOK(t *testing.T) {
}
}

func (s) TestFromErrorWrapped(t *testing.T) {
code, message := codes.Internal, "test description"
err := fmt.Errorf("wrapped error: %w", Error(code, message))
s, ok := FromError(err)
if !ok || s.Code() != code || s.Message() != message || s.Err() == nil {
t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q, Err()!=nil>, true", err, s, ok, code, message)
}
}

func (s) TestCode(t *testing.T) {
code, message := codes.Internal, "test description"
err := Error(code, message)
if s := Code(err); s != code {
t.Fatalf("Code(%v) = %v; want <Code()=%s>", err, s, code)
}
}

func (s) TestCodeOK(t *testing.T) {
if s, code := Code(nil), codes.OK; s != code {
t.Fatalf("Code(%v) = %v; want <Code()=%s>", nil, s, code)
}
}

func (s) TestCodeWrapped(t *testing.T) {
code, message := codes.Internal, "test description"
err := fmt.Errorf("wrapped: %w", Error(code, message))
if s := Code(err); s != code {
t.Fatalf("Code(%v) = %v; want <Code()=%s>", err, s, code)
}
}

type customError struct {
Code codes.Code
Message string
Expand Down

0 comments on commit 870f983

Please sign in to comment.