Go: returning from defer

旧城冷巷雨未停 提交于 2019-11-29 21:00:59

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
    }
}()
fang jinxu

have a look at this

package main

import "fmt"

func iWillPanic() {
    panic("ops, panic")
}
func runner() (s string) {
    rtnValue := ""
    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 rtnValue
}

func main() {
    fmt.Println("Return Value:", runner())
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!