Go:从 defer 中返回 [英] Go: returning from defer
本文介绍了Go:从 defer 中返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果函数发生恐慌(在 Go 中),我想从函数返回错误:
I want to return an error from a function if it panics (in Go):
func getReport(filename string) (rep report, err error) {
rep.data = make(map[string]float64)
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
err, _ = r.(error)
return nil, err
}
}()
panic("Report format not recognized.")
// rest of the getReport function, which can try to out-of-bound-access a slice
...
}
我似乎误解了恐慌和推迟的概念.有谁能赐教吗?
I appear to have misunderstood the very concept of panic and defer. Can anybody enlighten me?
推荐答案
在延迟函数中,您可以更改返回的参数,但不能返回新的集合.因此,对您现有的内容进行简单的更改即可使其发挥作用.
In a deferred function you can alter the returned parameters, but you can't return a new set. So a simple change to what you have will make it work.
你写的还有另一个问题,即你对 string
感到恐慌,但在你的类型断言中期望 error
.
There is another problem with what you wrote, namely that the you've paniced with a string
but are expecting an error
in your type assertion.
这是对这两者的修复(Play)
Here is a fix for both of those (Play)
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
// find out exactly what the error was and set err
switch x := r.(type) {
case string:
err = errors.New(x)
case error:
err = x
default:
err = errors.New("Unknown panic")
}
// invalidate rep
rep = nil
// return the modified err and rep
}
}()
这篇关于Go:从 defer 中返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文