Skip to content

Commit 724240f

Browse files
authored
fix: consistent handling of nil passed to any wrapping function (#4)
* fix: consistent handling of nil passed to any wrapping function * Document nil handling in `Wrap`, `WithStack` and `WithCause`
1 parent 541a584 commit 724240f

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ func Foo() error {
2828

2929
### Adding stack trace
3030
If you are interested in adding information about the line and filename where the sentinel error happened, you can do the following:
31+
32+
**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.
3133
```go
3234
func Foo() error {
3335
...
@@ -47,6 +49,8 @@ func Bar() error {
4749

4850
### Adding error cause information
4951
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:
52+
53+
**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.
5054
```go
5155
func FetchSomething(ID string) error {
5256
err := doSomething() // Here we have an error
@@ -74,6 +78,8 @@ func FooBar() error {
7478

7579
### Wrapping an error with a high-level message
7680
Sometimes you might want to add some high-level information to an error before passing it up to the invoker.
81+
82+
**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.
7783
```go
7884
func LoadProfile() error {
7985
err := makeAnApiCall()

errors.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ func New(message string, details ...any) error {
4444

4545
// Wrap returns a new errkitError that has the given message and err as the cause.
4646
func Wrap(err error, message string, details ...any) error {
47+
if err == nil {
48+
return nil
49+
}
50+
4751
e := newError(errors.New(message), 2, details...)
4852
e.cause = err
4953
return e

errors_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,16 @@ func TestErrorsWrapping(t *testing.T) {
286286
if wrappedErr != nil {
287287
t.Errorf("nil expected to be returned")
288288
}
289+
290+
wrappedErr = errkit.Wrap(nil, "Some message")
291+
if wrappedErr != nil {
292+
t.Errorf("nil expected to be returned")
293+
}
294+
295+
wrappedErr = errkit.WithStack(nil)
296+
if wrappedErr != nil {
297+
t.Errorf("nil expected to be returned")
298+
}
289299
})
290300
}
291301

0 commit comments

Comments
 (0)