在延迟函数中如何处理错误?

huangapple go评论112阅读模式
英文:

How do I handle errors in a deferred function?

问题

  1. func someFunc() (err error) {
  2. defer func(err_ error) {
  3. handleErrOrPanic(err_, obj)
  4. }(err) // 这里的 err 总是 nil
  5. err = ThrowErrOrPanic(ctx, obj)
  6. return err
  7. }

我想将 handleErrOrPanic 作为延迟函数来处理错误或恐慌。我必须在 ThrowErrOrPanic 之前定义它,因为延迟函数必须处理恐慌。然而,如果我在 err 之前定义它,err 总是为 nil。我该如何解决这个问题?

英文:
  1. func someFunc() (err error) {
  2. defer func(err_ error) {
  3. r.handleErrOrPanic(err_, obj)
  4. }(err) // err is always nil here
  5. err = ThrowErrOrPanic(ctx, obj)
  6. return err
  7. }

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()

  1. func someFunc() (err error) {
  2. defer func() {
  3. if x := recover(); x != nil { // 发生了恐慌?
  4. // 处理恐慌
  5. } else if err != nil { // 发生了普通错误?
  6. // 处理错误
  7. } else {
  8. // 一切正常
  9. }
  10. }()
  11. err = ThrowErrOrPanic(ctx, obj)
  12. return err
  13. }

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.

  1. func someFunc() (err error) {
  2. defer func() {
  3. if x := recover(); x != nil { // panic occurred?
  4. // handle panic
  5. } else if err != nil { // a plain error occurred?
  6. // handle error
  7. } else {
  8. // all good
  9. }
  10. }()
  11. err = ThrowErrOrPanic(ctx, obj)
  12. return err
  13. }

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

huangapple
  • 本文由 发表于 2022年9月26日 22:33:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/73855706.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定