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 Feb 17, 2023
1 parent abff344 commit 6cc3ab3
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
11 changes: 5 additions & 6 deletions status/status.go
Original file line number Diff line number Diff line change
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,9 +109,9 @@ func Code(err error) codes.Code {
if err == nil {
return codes.OK
}
if se, ok := err.(interface {
GRPCStatus() *Status
}); ok {

var se interface{ GRPCStatus() *Status }
if errors.As(err, &se) {
return se.GRPCStatus().Code()
}
return codes.Unknown
Expand Down
32 changes: 32 additions & 0 deletions status/status_test.go
Original file line number Diff line number Diff line change
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 6cc3ab3

Please sign in to comment.