From 5ea0bbcfe0c30d68a59a5846dd4f5b3bcc83154e Mon Sep 17 00:00:00 2001 From: Eugen Sumin Date: Tue, 19 Mar 2024 10:43:52 +0100 Subject: [PATCH 1/2] fix: consistent handling of nil passed to any wrapping function --- errors.go | 4 ++++ errors_test.go | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/errors.go b/errors.go index 4edc764..a2b9d0f 100644 --- a/errors.go +++ b/errors.go @@ -44,6 +44,10 @@ func New(message string, details ...any) error { // Wrap returns a new errkitError that has the given message and err as the cause. func Wrap(err error, message string, details ...any) error { + if err == nil { + return nil + } + e := newError(errors.New(message), 2, details...) e.cause = err return e diff --git a/errors_test.go b/errors_test.go index 5d6a736..c6d851a 100644 --- a/errors_test.go +++ b/errors_test.go @@ -286,6 +286,16 @@ func TestErrorsWrapping(t *testing.T) { if wrappedErr != nil { t.Errorf("nil expected to be returned") } + + wrappedErr = errkit.Wrap(nil, "Some message") + if wrappedErr != nil { + t.Errorf("nil expected to be returned") + } + + wrappedErr = errkit.WithStack(nil) + if wrappedErr != nil { + t.Errorf("nil expected to be returned") + } }) } From e8dc80ea9553902b28aa2e6fa8e501a36e4aa712 Mon Sep 17 00:00:00 2001 From: Eugen Sumin Date: Wed, 20 Mar 2024 11:47:49 +0100 Subject: [PATCH 2/2] Document nil handling in `Wrap`, `WithStack` and `WithCause` --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index a5b6b95..882bd60 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ func Foo() error { ### Adding stack trace If you are interested in adding information about the line and filename where the sentinel error happened, you can do the following: + +**NOTE**: While the `WithStack` will return `nil` if passed `err` equals `nil`, we do not consider this good practice and recommend checking the `err` value before invocation. ```go func Foo() error { ... @@ -47,6 +49,8 @@ func Bar() error { ### Adding error cause information Sometimes you might be interested in returning a sentinel error, but also add some cause error to it, in such cases you can do the following: + +**NOTE**: While the `WithCause` will return `nil` if passed `err` equals `nil`, we do not consider this good practice and recommend checking the `err` value before invocation. ```go func FetchSomething(ID string) error { err := doSomething() // Here we have an error @@ -74,6 +78,8 @@ func FooBar() error { ### Wrapping an error with a high-level message Sometimes you might want to add some high-level information to an error before passing it up to the invoker. + +**NOTE**: While the `Wrap` will return `nil` if passed `err` equals `nil`, we do not consider this good practice and recommend checking the `err` value before invocation. ```go func LoadProfile() error { err := makeAnApiCall()