I was so surprised by the design choice to need to put recover in in deferred function calls. It’s crazy to smush together the error handling and normal execution code.
I was so surprised by the design choice to need to put recover in in deferred function calls. It’s crazy to smush together the error handling and normal execution code.
Assuming recover has to exist, I think forcing it to be in a deferred function is genius because it composes so well with how defers work in go. It's guaranteed to run "when the function returns" which is exactly the time to catch such truly catastrophic behaviors.
func Foo() { try { maybePanic() } catch (err any) { doSomething(err) }
.. more code
}vs
func Foo() { defer func() { if err := recover(); err != nil { doSomething(err) } }()
maybePanic()
.. more code
}
Until go1.23 [0], Recover() comes in handy for fault reports, however; ex: https://github.com/hashicorp/terraform/blob/325d18262e/inter...
[0] which introduced debug.SetCrashOutput: https://pkg.go.dev/runtime/debug#SetCrashOutput