将恢复传递给上层goroutine golang

时间:2015-04-05 13:36:17

标签: go

我创建了一个示例,其中我同时运行函数,在其中我恐慌并恢复:

package main

import "fmt"

func main() {
    // "main" recovery
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("main goroutine paniced:", r)
        }
    }()

    // running function concurrently inside which I panic
    chanStr := make(chan string)
    go func() {
        // this "internal" goroutin recovery
        defer func() {
            if r := recover(); r != nil {
                fmt.Println("internal goroutine paniced:", r)
            }
            chanStr <- "hello world"
        }()
        // panicking and wanting recovery not only in "internal" recovery but in "main" recovery as well
        panic("NOT main goroutine")
    }()
    // waiting for chan with "internal" goroutine panicking and recovery
    str := <-chanStr
    fmt.Println(str)

    // panic("main")
}

它提供输出:

internal goroutine panicked: NOT main goroutine
hello world

是否可以更改我的代码以从&#34;内部&#34;到&#34;主要&#34;?换句话说,我希望它写下来到控制台:

internal goroutine paniced: NOT main goroutine
main goroutine paniced: main
hello world

我试图通过删除&#34;内部&#34;来实现这一点。恢复功能,但&#34;主要&#34;恢复不会恢复内部恐慌&#34;内部&#34;在这种情况下goroutine。

Playground

更新

我试图关注@ Momer的建议并通过频道发送错误并在主要的goroutine中处理它,而不是试图让恐慌起来:

package main

import (
    "errors"
    "fmt"
)

func main() {
    // "main" recovery
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("main goroutine paniced:", r)
        }
    }()

    // running func concarantly inside which I panic
    chanStr := make(chan string)
    chanErr := make(chan error)
    var err error
    go func() {
        // this "internal" goroutin recovery
        defer func() {
            if r := recover(); r != nil {
                fmt.Println("internal goroutine paniced:", r)
                switch t := r.(type) {
                case string:
                    fmt.Println("err is string")
                    err = errors.New(t)
                case error:
                    fmt.Println("err is error")
                    err = t
                default:
                    fmt.Println("err is unknown")
                    err = errors.New("Unknown error")
                }

                chanErr <- err
                chanStr <- ""
            }
        }()
        // panicing and wanting recovery not only in "internal" recovery but in "main" recovery as well
        panic("NOT main goroutine")
        chanStr <- "hello world"
        chanErr <- nil

    }()
    // waiting for chan with "internal" goroutin panicing and recovery
    str := <-chanStr
    err = <-chanErr
    fmt.Println(str)
    fmt.Println(err)

    // panic("main")
}

它给出了错误

all goroutines are asleep - deadlock

完整输出:

go run /goPath/parentRecoverty2.go
internal goroutine paniced: NOT main goroutine
err is string
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /goPath/parentRecoverty2.go:48 +0x1d4

goroutine 5 [chan send]:
main.func·002()
    /goPath/parentRecoverty2.go:37 +0x407
main.func·003()
    /goPath/parentRecoverty2.go:42 +0x130
created by main.main
    /goPath/parentRecoverty2.go:46 +0x190
exit status 2

Update playground

2 个答案:

答案 0 :(得分:1)

在您更新的问题中,通过写入chanStr来阻止一个线程,同时通过写入chanErr阻止另一个线程被阻止。 切换写入顺序应解决死锁问题。

defer func() {
    if r := recover(); r != nil {
        fmt.Println("internal goroutine paniced:", r)
        switch t := r.(type) {
        case string:
            fmt.Println("err is string")
            err = errors.New(t)
        case error:
            fmt.Println("err is error")
            err = t
        default:
            fmt.Println("err is unknown")
            err = errors.New("Unknown error")
        }
        chanStr <- ""
        chanErr <- err
    }
}

答案 1 :(得分:1)

我把golang中的恐慌/恢复作为java或c ++中的try / catch / final块。

有关详细信息,请访问Handling panics (from Golang spec)

所以你可以将恐慌传递给方法的来电者。 下面是一个简单的代码,希望有所帮助

注意:在函数Foo()中,我使用recover()来捕获出错的东西,然后重新发生混乱,以便稍后在外部调用者中捕获它。

package main

import (
    "fmt"
    "time"
)

func Foo() {
    defer func() {
        if x := recover(); x != nil {
            fmt.Printf("Runtime panic: %v \n", x)
            panic("Ah oh ... Panic in defer")
        }
    }()
    panic("Panic in Foo() !")
}

func Game() {
    defer func(){
        fmt.Println("Clean up in Game()")
    }()

    defer func() {
        if x := recover(); x != nil {
            fmt.Println("Catch recover panic !!! In Game()")
        }
    }()
    Foo()

}

func main() {

    defer func() {
        fmt.Println("Program Quit ... ")
    }()

    fmt.Println("-----------Split-------------")
    go Game()
    time.Sleep(1 * time.Millisecond)
    fmt.Println("-----------Split-------------")
}