diff --git a/lib/atexit/atexit.go b/lib/atexit/atexit.go index 1976d5a2a..d52d50371 100644 --- a/lib/atexit/atexit.go +++ b/lib/atexit/atexit.go @@ -77,3 +77,23 @@ func Run() { } }) } + +// OnError registers fn with atexit and returns a function which +// runs fn() if *perr != nil and deregisters fn +// +// It should be used in a defer statement normally so +// +// defer OnError(&err, cancelFunc)() +// +// So cancelFunc will be run if the function exits with an error or +// at exit. +func OnError(perr *error, fn func()) func() { + handle := Register(fn) + return func() { + defer Unregister(handle) + if *perr != nil { + fn() + } + } + +}