常见的坑

tip

go 捕获协程中的panic

goroutine发生panic,只有自身能够recover,其它goroutine是抓不到的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package test

import (
"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)
}

如上是不能捕获到异常的,需要如下处理在协程中捕获

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package test

import (
"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)
}