In a defer function, I want to see whether a call to recover would yield a non-nil value (without recovering)
Is it possible?
That exact thing isn't possible. You probably just want to re-panic, basically like re-throwing an exception in other languages;
defer func() {
if e := recover(); e != nil {
//log and so other stuff
panic(e)
}
}()
You can set a bool flag and then reset it at the end of the body of your function. If the flag is still set inside defer, you know that the last statement did not execute. The only possible reason for that is that the function is panicking.
https://play.golang.org/p/PKeP9s-3tF
func do() {
panicking := true
defer func() {
if panicking {
fmt.Println("recover would return !nil here")
}
}()
doStuff()
panicking = false
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With