Home > Software engineering >  How do I handle errors in a deferred function?
How do I handle errors in a deferred function?

Time:09-28

func someFunc() (err error) {
    defer func(err_ error) {
        r.handleErrOrPanic(err_, obj) 
    }(err) // err is always nil here
    err = ThrowErrOrPanic(ctx, obj)
    return err
}

I would like to use handleErrOrPanic as a deferred function to handle the error or the panic. I have to define it before ThrowErrOrPanic, since the deferred function has to handle the panic. However, if I define it before err is always nil. How do I solve this?

CodePudding user response:

In the deferred func use the named return value of the surrounding function, i.e. use err not err_. If you got panic and you want to recover from it use recover() in the deferred func.

func someFunc() (err error) {
    defer func() {
        if x := recover(); x != nil { // panic occurred?
            // handle panic
        } else if err != nil { // a plain error occurred?
            // handle error
        } else {
            // all good
        }
    }()

    err = ThrowErrOrPanic(ctx, obj)
    return err
}

https://go.dev/play/p/miTr-lN1Y9R

  • Related