Skip to content

Commit 4459990

Browse files
burdiyansywhang
andauthored
Add a shorthand for AppendInvoke (#65)
I really like the idea of catching returned errors from deferred functions. Though having to use `multierr` package name twice in the same line makes it a bit verbose in many occasions. This PR introduces a shorthand for AppendInvoke which allows passing function or method value directly without wrapping it into an Invoker. So this: ```go defer multierr.AppendInvoke(&err, multierr.Invoke(my.StopFunc)) ``` could become this: ```go defer multierr.AppendFunc(&err, my.StopFunc) ``` Co-authored-by: Sung Yoon Whang <[email protected]>
1 parent 80b07a7 commit 4459990

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

error.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -660,3 +660,22 @@ func Close(closer io.Closer) Invoker {
660660
func AppendInvoke(into *error, invoker Invoker) {
661661
AppendInto(into, invoker.Invoke())
662662
}
663+
664+
// AppendFunc is a shorthand for [AppendInvoke].
665+
// It allows using function or method value directly
666+
// without having to wrap it into an [Invoker] interface.
667+
//
668+
// func doSomething(...) (err error) {
669+
// w, err := startWorker(...)
670+
// if err != nil {
671+
// return err
672+
// }
673+
//
674+
// // multierr will call w.Stop() when this function returns and
675+
// // if the operation fails, it appends its error into the
676+
// // returned error.
677+
// defer multierr.AppendFunc(&err, w.Stop)
678+
// }
679+
func AppendFunc(into *error, fn func() error) {
680+
AppendInvoke(into, Invoke(fn))
681+
}

error_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -675,6 +675,24 @@ func TestAppendIntoNil(t *testing.T) {
675675
})
676676
}
677677

678+
func TestAppendFunc(t *testing.T) {
679+
var (
680+
errDeferred = errors.New("deferred func called")
681+
errOriginal = errors.New("original error")
682+
)
683+
684+
stopFunc := func() error {
685+
return errDeferred
686+
}
687+
688+
err := func() (err error) {
689+
defer AppendFunc(&err, stopFunc)
690+
691+
return errOriginal
692+
}()
693+
assert.Equal(t, []error{errOriginal, errDeferred}, Errors(err), "both deferred and original error must be returned")
694+
}
695+
678696
func errorPtr(err error) *error {
679697
return &err
680698
}

0 commit comments

Comments
 (0)