常见的坑 发表于 2019-12-16 | 分类于 go 字数统计: | 阅读时长 ≈ tipgo 捕获协程中的panicgoroutine发生panic,只有自身能够recover,其它goroutine是抓不到的 123456789101112131415161718192021package testimport ( "fmt" "testing" "time")func Test_Panic(t *testing.T) { defer func() { if r := recover(); r != nil { fmt.Println("out捕获到的错误", r) } }() go func() { fmt.Println("hello") time.Sleep(time.Second) panic("error") }() time.Sleep(time.Hour)} 如上是不能捕获到异常的,需要如下处理在协程中捕获 1234567891011121314151617181920212223242526package testimport ( "fmt" "testing" "time")func Test_Panic(t *testing.T) { defer func() { if r := recover(); r != nil { fmt.Println("out捕获到的错误", r) } }() go func() { defer func() { if r := recover(); r != nil { fmt.Println("in捕获到的错误:", r) } }() fmt.Println("hello") time.Sleep(time.Second) panic("error") }() time.Sleep(time.Hour)}