From f969bfaf50d095713e17a10edd0e3534ba2fa9f6 Mon Sep 17 00:00:00 2001 From: Georges Varouchas Date: Sat, 17 Oct 2020 15:22:37 +0200 Subject: [PATCH] implement ".Unwrap() error" on Error type (#2525) (#2526) Co-authored-by: Bo-Yi Wu Co-authored-by: thinkerou --- errors.go | 5 +++++ errors_1.13_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 errors_1.13_test.go diff --git a/errors.go b/errors.go index 9a317992..0f276c13 100644 --- a/errors.go +++ b/errors.go @@ -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 { diff --git a/errors_1.13_test.go b/errors_1.13_test.go new file mode 100644 index 00000000..a8f9a94e --- /dev/null +++ b/errors_1.13_test.go @@ -0,0 +1,33 @@ +// +build go1.13 + +package gin + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +type TestErr string + +func (e TestErr) Error() string { return string(e) } + +// TestErrorUnwrap tests the behavior of gin.Error with "errors.Is()" and "errors.As()". +// "errors.Is()" and "errors.As()" have been added to the standard library in go 1.13, +// hence the "// +build go1.13" directive at the beginning of this file. +func TestErrorUnwrap(t *testing.T) { + innerErr := TestErr("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 TestErr + assert.True(t, errors.As(err, &testErr)) +}