Skip to content

Commit

Permalink
Add status.Convert convenience function (grpc#1848)
Browse files Browse the repository at this point in the history
This commit adds a function to convert between gRPC errors to
status.Status types without having to deal with an "ok" return value.
  • Loading branch information
enocom authored and dfawley committed Feb 8, 2018
1 parent 365770f commit d50734d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
12 changes: 10 additions & 2 deletions status/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,15 +120,23 @@ func FromProto(s *spb.Status) *Status {
}

// FromError returns a Status representing err if it was produced from this
// package, otherwise it returns nil, false.
// package. Otherwise, ok is false and a Status is returned with codes.Unknown
// and the original error message.
func FromError(err error) (s *Status, ok bool) {
if err == nil {
return &Status{s: &spb.Status{Code: int32(codes.OK)}}, true
}
if se, ok := err.(*statusError); ok {
return se.status(), true
}
return nil, false
return New(codes.Unknown, err.Error()), false
}

// Convert is a convenience function which removes the need to handle the
// boolean return value from FromError.
func Convert(err error) *Status {
s, _ := FromError(err)
return s
}

// WithDetails returns a new status with the provided details messages appended to the status.
Expand Down
27 changes: 27 additions & 0 deletions status/status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,33 @@ func TestFromErrorOK(t *testing.T) {
}
}

func TestFromErrorUnknownError(t *testing.T) {
code, message := codes.Unknown, "unknown error"
err := errors.New("unknown error")
s, ok := FromError(err)
if ok || s.Code() != code || s.Message() != message {
t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q>, false", err, s, ok, code, message)
}
}

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

func TestConvertUnknownError(t *testing.T) {
code, message := codes.Unknown, "unknown error"
err := errors.New("unknown error")
s := Convert(err)
if s.Code() != code || s.Message() != message {
t.Fatalf("Convert(%v) = %v; want <Code()=%s, Message()=%q>", err, s, code, message)
}
}

func TestStatus_ErrorDetails(t *testing.T) {
tests := []struct {
code codes.Code
Expand Down

0 comments on commit d50734d

Please sign in to comment.