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

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

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
}

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:

确定