Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

function to return next referenced error object #45

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions multierror.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,12 @@ func (e chain) As(target interface{}) bool {
func (e chain) Is(target error) bool {
return errors.Is(e[0], target)
}

func Unwrap(wraperr error) (chainErr error, err error) {
c, ok := errors.Unwrap(wraperr).(chain)
if !ok {
return nil, nil
}

return c, c[0]
}
48 changes: 48 additions & 0 deletions multierror_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package multierror

import (
"database/sql"
"errors"
"fmt"
"reflect"
Expand Down Expand Up @@ -197,6 +198,53 @@ func TestErrorAs(t *testing.T) {
})
}

func TestPackageUnwrap(t *testing.T) {
t.Run("with reference checking", func(t *testing.T) {
err := &Error{Errors: []error{
errors.New("foo"),
errors.New("bar"),
errors.New("baz"),
}}

var currentChain error = err
var errorRef error

for i := 0; i < len(err.Errors); i++ {
currentChain, errorRef = Unwrap(currentChain)

if errorRef != err.Errors[i] {
t.Fatal("invalid be equal")
}
}

if chain, err := Unwrap(currentChain); chain != nil || err != nil {
t.Fatal("should be nil at the end")
}
})

t.Run("with switch cases", func(t *testing.T) {
UserNotExistsErr := errors.New("user not exists")

fakeAddUser := func() error {
return Append(UserNotExistsErr, sql.ErrNoRows)
}

err := fakeAddUser()

switch chainErr, err := Unwrap(err); err {
case UserNotExistsErr:
switch _, err := Unwrap(chainErr); err {
case sql.ErrNoRows:
default:
t.Errorf("should be sql.ErrNoRows")
}
default:
t.Errorf("should be UserNotExistsErr err")
}
})

}

// nestedError implements error and is used for tests.
type nestedError struct{}

Expand Down