Defer also encourages the unsafe behavior of not checking error results. You can't propagate errors from it. About the best you can do is wrap whatever function you were deferring in another function, and then panic if there is an error.
func Pants() (rerr error) {
defer func() {
if err := doStuff(); err != nil && rerr == nil {
rerr = err
}
}()
// ...
return nil
}
I use this function all the time with `io.Closer` implementations: func DeferClose(err *error, closer io.Closer) {
cerr := closer.Close()
if *err == nil && cerr != nil {
*err = cerr
}
}
func Pants() (rerr error) {
f, _ := os.Open(...)
defer errtools.DeferClose(&rerr, f)
// ...
return nil
}