5 ms·
Or, if you really hate duplication, you could optionally do something like this, where you extract the common error handling into a closure: handleError :=
by coder543 2y ago
Or, if you really hate duplication, you could optionally do something like this, where you extract the common error handling into a closure:
handleError := func(origErr error, context string) error {
c, err := h()
if err != nil {
return fmt.Errorf("%s: h failed: %w", context, err)
}
cleanupC(c)
return fmt.Errorf("%s: %w", context, origErr)
}
a, err := f()
if err != nil {
return handleError(err, "f failed")
}
defer cleanupA(a)
b, err := a.g()
if err != nil {
return handleError(err, "a.g failed")
}
defer cleanupB(b)
// the rest of the function continues after here