Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for panic without recovering from it

In a defer function, I want to see whether a call to recover would yield a non-nil value (without recovering)

Is it possible?

like image 613
Danyel Avatar asked May 05 '15 20:05

Danyel


2 Answers

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)
             }
          }()
like image 108
evanmcdonnal Avatar answered Sep 20 '22 02:09

evanmcdonnal


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
}
like image 27
user7610 Avatar answered Sep 21 '22 02:09

user7610