diff --git a/CHANGELOG.md b/CHANGELOG.md index 9389d11..090e674 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Valkyrie - Changelog +## v0.1.0 (2020-MAY-27) +- supports method Cause +- supports method Unwrap for Go 1.13 error chains + ## v0.0.1 (2018-JAN-19) - initial fork commit diff --git a/multierror.go b/multierror.go index 99bba8f..95a978d 100644 --- a/multierror.go +++ b/multierror.go @@ -43,3 +43,20 @@ func (m *MultiError) Error() string { return strings.Join(formattedError, ", ") } + +// Cause returns the first original error. +func (m *MultiError) Cause() error { + m.mutex.Lock() + defer m.mutex.Unlock() + + if len(m.errs) == 0 { + return nil + } + + return m.errs[0] +} + +// Unwrap provides compatibility for go 1.13 error chains. +func (m *MultiError) Unwrap() error { + return m.Cause() +} diff --git a/multierror_test.go b/multierror_test.go index dae1db3..40d7241 100644 --- a/multierror_test.go +++ b/multierror_test.go @@ -56,3 +56,29 @@ func TestMultiErrorWhileConcurrentPushShouldNotPanic(t *testing.T) { } assert.NotPanics(t, concurrentPushAndErrors) } + +func TestMultiError_Cause(t *testing.T) { + me := &MultiError{} + assert.NoError(t, me.Cause()) + + me.Push("one") + me.Push("two") + me.Push("three") + + err := me.Cause() + assert.Error(t, err) + assert.Equal(t, "one", err.Error()) +} + +func TestMultiError_Unwrap(t *testing.T) { + me := &MultiError{} + assert.NoError(t, me.Unwrap()) + + me.Push("one") + me.Push("two") + me.Push("three") + + err := me.Unwrap() + assert.Error(t, err) + assert.Equal(t, "one", err.Error()) +}