是否有可能从恐慌中的恐慌中恢复过来?

时间:2016-01-16 08:14:32

标签: go

恐慌情绪似乎无法从恐慌中恢复过来?

func TestError(t *testing.T) {

    e := &myErr{p: false}
    fmt.Println(e.Error())  // this prints "returned"
    panic(e)                // this prints "panic: returned"

    e1 := &myErr{p: true}
    fmt.Println(e1.Error()) // this prints "recovered"
    panic(e1)               // this prints "panic: panic: paniced
                            //              fatal error: panic holding locks 
                            //              panic during panic"
}

type myErr struct {
    p bool
}

func (m *myErr) Error() (out string) {
    defer func() {
        if r := recover(); r != nil {
            out = "recovered"
        }
    }()
    if m.p {
        panic("paniced")
    }
    return "returned"
}

Backstory:我的错误Error()函数使用os.Getwd,在恐慌中似乎总是恐慌,所以我想优雅地处理它。

1 个答案:

答案 0 :(得分:0)

我认为它可以解决您的问题,以替换此

panic(e1)

由此

panic(e1.Error())

游乐场:http://play.golang.org/p/fXpX2ch9eF

这里的问题很有意思:为什么?这是困难的部分,我不知道确切的答案。可能这里的问题是我们在执行了所有被保护的函数后进行惊慌(所以当Go确实尝试打印恐慌错误字符串时)。如果不正确,欢迎任何更正!

相关问题