Something like this:
a, err := f()
if err != nil {
c, err := h()
if err != nil {
return fmt.Errorf("h failed: %w", err)
}
cleanupC(c)
return fmt.Errorf("f failed: %w", err)
}
defer cleanupA(a)
b, err := a.g()
if err != nil {
c, err := h()
if err != nil {
return fmt.Errorf("h failed: %w", err)
}
cleanupC(c)
return fmt.Errorf("a.g failed: %w", err)
}
defer cleanupB(b)
// the rest of the function continues after here
It’s not crazy.With Java’s checked exceptions, you at least have the compiler helping you to know (most of) what needs to be handled, compared to languages that just expect you to find out what exceptions explode through guess and check… but some would argue that you should only handle the happy path and let the entire handler die when something goes wrong.
I generally prefer the control flow that languages like Rust, Go, and Swift use.
Errors are rarely exceptional. Why should we use exceptions to handle all errors? Most errors are extremely expected, the same as any other value.
I’m somewhat sympathetic to the Erlang/Elixir philosophy of “let it crash”, where you have virtually no error handling in most of your code (from what I understand), but it is a very different set of trade offs.
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