Go: returning from defer

2019-01-31 02:37发布

I want to return an error from a function if it panics (in Go):

func getReport(filename string) (rep report, err error) {
    rep.data = make(map[string]float64)

    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in f", r)
            err, _ = r.(error)
            return nil, err
        }
    }()
    panic("Report format not recognized.")
    // rest of the getReport function, which can try to out-of-bound-access a slice
    ...
} 

I appear to have misunderstood the very concept of panic and defer. Can anybody enlighten me?

标签: go return panic
2条回答
手持菜刀,她持情操
2楼-- · 2019-01-31 03:13

have a look at this

package main

import "fmt"

func iwillpanic() {
    panic("ops, panic")
}
func runner() (s string) {
    rtn_value := ""
    defer func() {
        if r := recover(); r != nil {
            // and your logs or something here, log nothing with panic is not a good idea
            s = "don't panic" // modify the return value, and it will return
        }
    }()
    iwillpanic()
    return rtn_value
}

func main() {
    fmt.Println("Return Value:", runner())
}
查看更多
Summer. ? 凉城
3楼-- · 2019-01-31 03:30

In a deferred function you can alter the returned parameters, but you can't return a new set. So a simple change to what you have will make it work.

There is another problem with what you wrote, namely that the you've paniced with a string but are expecting an error in your type assertion.

Here is a fix for both of those (Play)

defer func() {
    if r := recover(); r != nil {
        fmt.Println("Recovered in f", r)
        // find out exactly what the error was and set err
        switch x := r.(type) {
        case string:
            err = errors.New(x)
        case error:
            err = x
        default:
            err = errors.New("Unknown panic")
        }
        // invalidate rep
        rep = nil
        // return the modified err and rep
    }
}()
查看更多
登录 后发表回答