Golang: checking for panic without recovering from it

In the snooze function, I want to see if the call will restore to a value other than zero (without recovery)

Is it possible?

+1
source share
3 answers

The exact thing is impossible. You probably just want to re-panic, basically like re-throwing an exception into other languages;

        defer func() {
             if e := recover(); e != nil {
                 //log and so other stuff
                 panic(e)
             }
          }
+6
source

You can set the bool flag and then reset at the end of your function body. If the flag is still set to defer, you know that the last statement was not executed. The only possible reason for this is that the function panics.

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
}
0
source

""

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)
}
-1
source

Source: https://habr.com/ru/post/1624687/


All Articles