如何在Go函数中返回一个值,使其发生恐慌? [英] How to return a value in a Go function that panics?

查看:138
本文介绍了如何在Go函数中返回一个值,使其发生恐慌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Go功能预计返回一个值,但在调用库函数时可能会发生混乱。我可以使用 recover()在延期通话中捕获此信息,但在这种情况下如何返回值?

My Go function is expected to return a value, but it may panic when calling a library function. 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?
}


推荐答案

您可以使用命名结果参数。命名您的返回值,并在检测到紧急时的延迟函数中,您可以更改返回变量的值。更改的新值将被返回。

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

示例:

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"
}

输出 Go Playground ):

Returned: was panic, recovered value: test

规格:延期陈述


例如,如果延迟函数是函数文字,并且周围的功能的命名结果参数属于范围内的文字,延期函数可以在返回结果参数之前访问和修改它们。

For instance, if the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned.

在博客文章 延迟,紧急和恢复

It is also mentioned in the blog post Defer, Panic and Recover:


延期函数可以读取并分配给返回函数的命名返回值。

Deferred functions may read and assign to the returning function's named return values.

而且在

And also in Effective Go: Recover:


如果 doParse panics,恢复块将返回值设置为 nil -deferred函数可以修改命名返回值。

If doParse panics, the recovery block will set the return value to nil—deferred functions can modify named return values.

这篇关于如何在Go函数中返回一个值,使其发生恐慌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆