The go runtime can detect panic(nil)
and reports an error.
However, I can't detect panic(nil)
with recover()
in a defer
red function because it returns nil
, so I cannot differentiate it from normal execution (no panic) as I would test for
the return value of recover()
to be nil.
For example,
defer func(){
var err = recover()
if err != nil {
// Real serious situation. Panic from inner code.
// And we may have some critical resources which
// must be cleaned-up at any cases.
// However, this will not be executed for panic(nil)
rollback()
// I am still not sure that how should I treat `panic`…
// Should I just ignore them?
}
}()
var err = doTransaction()
if err == nil {
commit() // Happy case.
} else {
rollback() // Regular execution. Just a lucky case.
}
ROLLBACK is just an example, and I think I can have plenty of critical cases needs cleanup. Well, those cleanup code won't be executed on real program crash too, but I want to defend as much as possible.
How can I detect any panic regardless of its parameter in a deferred function?