How to return a value to a Go function that panics?

The My Go function is expected to return, but may cause panic when the library function is called. I can use recover()to capture this in a deferred call, but how can I return a value in this case?

func MyFunc() string{
    defer func() {
        if err := recover(); err != nil {
            // What do I do to make MyFunc() return a value in case of panic?
        }
    }()
    SomeFuncThatMayPanic()
    return "Normal Return Value"
    // How can I return "ERROR" in case of panic?
}
+7
source share
2 answers

You can use named result parameters . Name your return values ​​and in the deferred function, when a panic was detected, you can change the values ​​of the returned "variables". Changed new values ​​will be returned.

Example:

func main() {
    fmt.Println("Returned:", MyFunc())
}

func MyFunc() (ret string) {
    defer func() {
        if r := recover(); r != nil {
            ret = fmt.Sprintf("was panic, recovered value: %v", r)
        }
    }()
    panic("test")
    return "Normal Return Value"
}

Exit (try on the Go Playground ):

Returned: was panic, recovered value: test

: :

, , , , .

, :

.

: :

doParse , nil -deferred .

+29

icza, , , , , , :

func main() {
    fmt.Println("Returned:", MyFunc()) // false
}

func MyFunc() (ret bool) {
    defer func() {
        if r := recover(); r != nil {
        }
    }()
    panic("test")
    return true
}

.

0

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


All Articles