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
}
The solution does not have "direct" paths
package main
import(
"fmt"
"runtime"
"regexp"
)
var re_runtimepanicdetector *regexp.Regexp = regexp.MustCompile("runtime/panic.go$");
func tester_for_panic( deferdepth int )bool{
_,file,_,_ := runtime.Caller(deferdepth+3)
return re_runtimepanicdetector.MatchString(file)
}
func tester_for_panic_worktest() bool {
defer func(){
recover() ;
if !tester_for_panic(0) { panic("tester_for_panic: NOT WORK!!") }
}();
panic(1)
}
var Iswork_tester_for_panic bool= tester_for_panic_worktest();
func testp( dopanic bool ) {
defer func() {
fmt.Println("defer panic=", tester_for_panic(0)) ;
recover() // optional
}()
if (dopanic) { panic("test") }
}
func main(){
testp(true)
testp(false)
}