From 38abe5b2a4ec5e296a6ab1be569425f8342753a6 Mon Sep 17 00:00:00 2001 From: "Derrick J. Wippler" Date: Fri, 30 Jun 2023 14:03:57 -0500 Subject: [PATCH] Added errors.Cause() (#6) --- go.mod | 2 -- go.sum | 4 ---- wrap.go | 12 ++++++++++++ wrap_test.go | 9 +++++++++ 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index 17301ba..a2b50e3 100644 --- a/go.mod +++ b/go.mod @@ -4,14 +4,12 @@ go 1.19 require ( github.com/ahmetb/go-linq v3.0.0+incompatible - github.com/mailgun/holster/v4 v4.11.0 github.com/sirupsen/logrus v1.9.0 github.com/stretchr/testify v1.8.1 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect - github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index d4ff782..508ca75 100644 --- a/go.sum +++ b/go.sum @@ -3,10 +3,6 @@ github.com/ahmetb/go-linq v3.0.0+incompatible/go.mod h1:PFffvbdbtw+QTB0WKRP0cNht github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/mailgun/holster/v4 v4.11.0 h1:c9DT3QZCfiUgcmOYvxJI9rRhLbtX6IqfaClrMjLxkLE= -github.com/mailgun/holster/v4 v4.11.0/go.mod h1:sXpF+rzEqA89uBEiX19FrVUdbCUKDfR4GRdXmIkINQQ= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= diff --git a/wrap.go b/wrap.go index 7aa9793..21c678a 100644 --- a/wrap.go +++ b/wrap.go @@ -1,6 +1,7 @@ package errors import ( + "errors" "fmt" "io" @@ -31,6 +32,17 @@ func Wrapf(err error, format string, a ...any) error { } } +// Cause returns the last error in the stack of wrapped errors. +func Cause(err error) error { + for { + wrapped := errors.Unwrap(err) + if wrapped == nil { + return err + } + err = wrapped + } +} + type wrappedError struct { msg string wrapped error diff --git a/wrap_test.go b/wrap_test.go index 77653eb..206f5d0 100644 --- a/wrap_test.go +++ b/wrap_test.go @@ -124,3 +124,12 @@ func TestWrapErrorValue(t *testing.T) { wrap := errors.Wrap(err, "message") assert.True(t, errors.Is(wrap, io.EOF)) } + +func TestCause(t *testing.T) { + err := errors.Errorf("error: %w", errors.Wrap(errors.Wrap(errors.New("the cause"), "wrap 2"), "wrap 1")) + cause := errors.Cause(err) + require.Error(t, err) + require.Error(t, cause) + assert.Equal(t, "error: wrap 1: wrap 2: the cause", err.Error()) + assert.Equal(t, "the cause", cause.Error()) +}