Capturing panic() in golang

后端 未结 3 568
别跟我提以往
别跟我提以往 2020-12-08 11:04

We have a large-ish golang application that uses the logger (actually, a custom logger), to write output to a log file that is periodically rotated.

However, when an

3条回答
  •  伪装坚强ぢ
    2020-12-08 11:38

    You can use recover() to recover panics from the same goroutine. When calling recover() in a deferred method (remember that deferred methods will still be called, even when panic()ing), it will return whatever was passed into the last panic() call as argument (or nil when the program is not panicking).

    defer func() {
        if x := recover(); x != nil {
            // recovering from a panic; x contains whatever was passed to panic()
            log.Printf("run time panic: %v", x)
    
            // if you just want to log the panic, panic again
            panic(x)
        }
    }()
    
    panic("foo");
    

    Note however, that you cannot recover from panics that were triggered in a different goroutine (thanks to JimB for the hint). Using a single recover() to recover from panics from any goroutine is not possible.

提交回复
热议问题