Can I recover from a panic, handle the error, and then panic again and save the original stack trace?

Is it possible to "repair" the error with recoverand keep the original stack trace? The best I know how to do this is to panic again, but this creates a new stack.

func do() {
    defer func() {
        cleanUp()
        if x := recover(); x != nil {
            handleError()
            panic(x)
        }
    }()
    doStuff()
}

My motivation for this is that if my function does not work out normally or handleErrorworks, my program will be blocked. And if I don’t save the original trace, I don’t know where it crashed.

+4
source share
2 answers

recover, , . bool recover, .

https://play.golang.org/p/PKeP9s-3tF

func do() {
    panicked := true
    defer func() {
        cleanUp()
        if panicked {
            handleError()
        }
    }()
    doStuff()
    panicked = false
}
+2

, recover().

if-statement . , .

func do() {
    defer handleError()
    doStuff()
}

:

https://play.golang.org/p/UiRou5MhUR

func a() {
    defer func() {
        fmt.Println("a")
    }()
    panic("test")
}
func b() {
    defer func() {
        fmt.Println("b")
    }()
}

func main() {
    fmt.Println("Hello, playground")
    b()
}

Hello, playground
b
+4

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


All Articles