Skip to content

Instantly share code, notes, and snippets.

@patryk4815
Created March 30, 2021 12:58
Show Gist options
  • Save patryk4815/ab34922402609ef200c32e7f4dcd7af8 to your computer and use it in GitHub Desktop.
Save patryk4815/ab34922402609ef200c32e7f4dcd7af8 to your computer and use it in GitHub Desktop.
package main
func goRecover(f func(), recovered chan<- error) {
go func() {
done := false // just to handle panic(nil) https://github.com/golang/go/issues/25448
defer func() {
if !done {
var errOut error
errAny := recover()
if err, ok := errAny.(error); ok {
// errors.Wrap adds stacktrace to error
errOut = errors.Wrap(err, "goRecover")
} else {
// errors.Errorf adds stacktrace to error
errOut = errors.Errorf("PANIC cast to error: %v", errAny)
}
recovered <- errOut
}
}()
f()
done = true
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment