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
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.