Skip to content

Commit

Permalink
implement ".Unwrap() error" on Error type (gin-gonic#2525)
Browse files Browse the repository at this point in the history
  • Loading branch information
LeGEC committed Oct 9, 2020
1 parent 540b1ef commit 8a570b9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
5 changes: 5 additions & 0 deletions errors.go
Expand Up @@ -90,6 +90,11 @@ func (msg *Error) IsType(flags ErrorType) bool {
return (msg.Type & flags) > 0
}

// Unwrap returns the wrapped error, to allow interoperability with errors.Is(), errors.As() and errors.Unwrap()
func (msg *Error) Unwrap() error {
return msg.Err
}

// ByType returns a readonly copy filtered the byte.
// ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic.
func (a errorMsgs) ByType(typ ErrorType) errorMsgs {
Expand Down
20 changes: 20 additions & 0 deletions errors_test.go
Expand Up @@ -6,6 +6,7 @@ package gin

import (
"errors"
"fmt"
"testing"

"github.com/gin-gonic/gin/internal/json"
Expand Down Expand Up @@ -104,3 +105,22 @@ Error #03: third
assert.Nil(t, errs.JSON())
assert.Empty(t, errs.String())
}

type TestStrErr string

func (e TestStrErr) Error() string { return string(e) }

func TestErrorUnwrap(t *testing.T) {
innerErr := TestStrErr("somme error")

// 2 layers of wrapping : use 'fmt.Errorf("%w")' to wrap a gin.Error{}, which itself wraps innerErr
err := fmt.Errorf("wrapped: %w", &Error{
Err: innerErr,
Type: ErrorTypeAny,
})

// check that 'errors.Is()' and 'errors.As()' behave as expected :
assert.True(t, errors.Is(err, innerErr))
var testErr TestStrErr
assert.True(t, errors.As(err, &testErr))
}

0 comments on commit 8a570b9

Please sign in to comment.