英文:
How do I handle errors in a deferred function?
问题
func someFunc() (err error) {
defer func(err_ error) {
handleErrOrPanic(err_, obj)
}(err) // 这里的 err 总是 nil
err = ThrowErrOrPanic(ctx, obj)
return err
}
我想将 handleErrOrPanic
作为延迟函数来处理错误或恐慌。我必须在 ThrowErrOrPanic
之前定义它,因为延迟函数必须处理恐慌。然而,如果我在 err
之前定义它,err
总是为 nil。我该如何解决这个问题?
英文:
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?
答案1
得分: 2
在延迟函数中使用包围函数的命名返回值,即使用err
而不是err_
。如果发生恐慌并且你想从中恢复,请在延迟函数中使用recover()
。
func someFunc() (err error) {
defer func() {
if x := recover(); x != nil { // 发生了恐慌?
// 处理恐慌
} else if err != nil { // 发生了普通错误?
// 处理错误
} else {
// 一切正常
}
}()
err = ThrowErrOrPanic(ctx, obj)
return err
}
https://go.dev/play/p/miTr-lN1Y9R
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论