goroutine异常捕获

package main

import (
    "log"
    "time"
)

//2021/03/01 00:22:02 start demo
//2021/03/01 00:22:02 recover goroutine err: this is a panic demo
//2021/03/01 00:22:05 end demo
func main() {
    log.Println("start demo")
    Go(PanicDemo)
    time.Sleep(3 * time.Second)
    log.Println("end demo")
}

func PanicDemo() {
    panic("this is a panic demo")
}

// 捕获异常的goroutine
func Go(x func()) {
    go func() {
        defer func() {
            if err := recover(); err != nil {
                log.Printf("recover goroutine err: %v", err)
            }
        }()

        // 执行goroutine
        x()
    }()
}

最后更新于

这有帮助吗?