Skip to content

Commit

Permalink
feat(unierr): allow nil errors (close #125) (#126)
Browse files Browse the repository at this point in the history
  • Loading branch information
GGXXLL committed Apr 27, 2021
1 parent 7192cff commit 6c3f812
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 3 deletions.
9 changes: 9 additions & 0 deletions unierr/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ func Newf(code codes.Code, format string, args ...interface{}) *Error {

// Wrap annotates an error with a codes.Code
func Wrap(err error, code codes.Code) *Error {
if err == nil {
return &Error{
msg: code.String(),
code: code,
}
}
err = errors.WithStack(err)
return &Error{
err: err,
Expand Down Expand Up @@ -181,6 +187,9 @@ type stackTracer interface {

// StackTrace implements the interface of errors.Wrap()
func (e *Error) StackTrace() errors.StackTrace {
if e.err == nil {
return nil
}
if err, ok := e.err.(stackTracer); ok {
return err.StackTrace()
}
Expand Down
66 changes: 63 additions & 3 deletions unierr/error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ package unierr

import (
"encoding/json"
"errors"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/codes"
"strings"
"testing"

"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/codes"
)

func TestServerError_UnmarshalJSON(t *testing.T) {
Expand Down Expand Up @@ -61,3 +62,62 @@ func TestServerError_CustomPrinter(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, []byte(`{"code":10,"message":"FOO"}`), bytes)
}

func TestWrap(t *testing.T) {
type args struct {
err error
code codes.Code
}
tests := []struct {
name string
args args
want string
}{
{"err_nil", args{nil, codes.Aborted}, codes.Aborted.String()},
{"err_foo", args{errors.New("foo"), codes.Aborted}, "foo"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
testError := Wrap(tt.args.err, tt.args.code)
assert.Equal(t, tt.want, testError.Error())
byts, err := json.Marshal(testError)
assert.NoError(t, err)
var result *Error
err = json.Unmarshal(byts, &result)
assert.NoError(t, err)
assert.Equal(t, testError.code, result.code)
assert.Equal(t, testError.msg, result.msg)
assert.True(t, IsAbortedErr(result))

status := testError.GRPCStatus()
assert.Equal(t, codes.Aborted, status.Code())
assert.Equal(t, testError.Error(), status.Message())

})
}
}

func TestError_StackTrace(t *testing.T) {
type args struct {
err error
code codes.Code
}
tests := []struct {
name string
args args
want int
}{
{"err_nil", args{nil, codes.Aborted}, 0},
{"err_foo", args{errors.New("foo"), codes.Aborted}, 3},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := &Error{
err: tt.args.err,
code: tt.args.code,
}
s := e.StackTrace()
assert.Equal(t, tt.want, len(s))
})
}
}

0 comments on commit 6c3f812

Please sign in to comment.