go使用recover()来捕捉panic(),防止程序崩溃

一、在协程中的panic(),导致整个程序崩溃

func TestPanic(t *testing.T) {
    t.Log("1")
    go func() {
        panic("panic")
    }()
    time.Sleep(time.Second * 1) //加一下,防止 多个协程(panic协程还没走到,主协程就结束了)
    t.Log("2")
}

输出:

1
panic: panic

goroutine 7 [running]:
github.com/hisheng/dataStructure/panic.TestPanic.func1()
    /Users/zhanghaisheng/study/dataStructure/panic/panic_test.go:16 +0x39
created by github.com/hisheng/dataStructure/panic.TestPanic
    /Users/zhanghaisheng/study/dataStructure/panic/panic_test.go:15 +0x85

我们可以看到,子协程的panic,直接导致了,主协程也蹦了,没法执行下去。

二、go使用recover()来捕捉panic(),防止程序崩溃

func TestRecover(t *testing.T) {
    t.Log("1")
    go func() {
        defer func() {
            recover()
        }()
        panic("panic")
    }()
    time.Sleep(time.Second * 1) //加一下,防止 多个协程(panic协程还没走到,主协程就结束了)
    t.Log("2")
}

输出:

1
2

三、go使用recover()来做一些逻辑处理

recover()有返回值,我们可以用 recover() != nil来做一些处理

//当panic的时候写入到日志里面
func TestRecover2(t *testing.T) {
    t.Log("1")
    go func() {
        defer func() {
            r := recover()
            if r != nil {
                //写入日志
            }
        }()
        panic("panic")
    }()
    time.Sleep(time.Second * 1) //加一下,防止 多个协程(panic协程还没走到,主协程就结束了)
    t.Log("2")
}

四、封装一个RecoverGo()来做一些逻辑处理

func RecoverGO(f func()) {
    go func() {
        defer func() {
            if r := recover(); r != nil {
                log.Printf("%+v", errors.Errorf("%+v", r))
            }
        }()
        f()
    }()
}

这样在调用的地方,使用如下,可以安全的使用协程,比如下面的function1()如果发生panic也不影响。

RecoverGO(func() {
    //业务逻辑1
    function1()
    //业务逻辑2
    function2()
})

谢谢您的观看,欢迎关注我的公众号。

image.png

评论

暂无评论