Skip to content

Commit

Permalink
Implement Go 1.13 error interfaces (flyteorg#44)
Browse files Browse the repository at this point in the history
* Implement Go 1.13 error interfaces

* Update comment
  • Loading branch information
EngHabu authored Oct 21, 2019
1 parent 2fc4339 commit 73b83f0
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 35 deletions.
71 changes: 36 additions & 35 deletions flytestdlib/Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions flytestdlib/errors/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ func (e *err) Code() ErrorCode {
return e.code
}

// Overrides Is to check for error code only. This enables the default package's errors.Is().
func (e *err) Is(target error) bool {
t, ok := target.(*err)
if !ok {
return false
}

return e.Code() == t.Code()
}

type errorWithCause struct {
*err
cause error
Expand All @@ -36,6 +46,11 @@ func (e *errorWithCause) Cause() error {
return e.cause
}

// Overrides Unwrap to retrieve the underlying error. This enables the default package's errors.Unwrap().
func (e *errorWithCause) Unwrap() error {
return e.Cause()
}

// Creates a new error using an error code and a message.
func Errorf(errorCode ErrorCode, msgFmt string, args ...interface{}) error {
return &err{
Expand Down
21 changes: 21 additions & 0 deletions flytestdlib/errors/error_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package errors

import (
"errors"
"fmt"
"testing"

Expand Down Expand Up @@ -45,3 +46,23 @@ func TestIsCausedByError(t *testing.T) {
assert.True(t, IsCausedByError(e2, eRoot))
assert.True(t, IsCausedByError(e2, e1))
}

func TestErrorsIs(t *testing.T) {
eRoot := Errorf("Code1", "msg")
assert.True(t, errors.Is(eRoot, Errorf("Code1", "different msg")))

e1 := Wrapf("Code2", eRoot, "Wrapped error")
assert.True(t, errors.Is(e1, Errorf("Code1", "different msg")))
}

func TestErrorsUnwrap(t *testing.T) {
eRoot := Errorf("Code1", "msg")
e1 := Wrapf("Code2", eRoot, "Wrapped error")
assert.True(t, errors.Is(e1, Errorf("Code1", "different msg")))

newErr := &err{}
assert.True(t, errors.As(e1, &newErr))
assert.Equal(t, "Code1", newErr.Code())

assert.True(t, errors.Is(errors.Unwrap(e1), Errorf("Code1", "different msg")))
}

0 comments on commit 73b83f0

Please sign in to comment.