Skip to content

Instantly share code, notes, and snippets.

@r3code
Created April 12, 2021 15:03
Show Gist options
  • Save r3code/6c5fc8bb9ac7a907bb06f802062333d2 to your computer and use it in GitHub Desktop.
Save r3code/6c5fc8bb9ac7a907bb06f802062333d2 to your computer and use it in GitHub Desktop.
Get last error with stack
// import gihub.com/pkg/errors
// Stack returns the last error in the error chain implementing StackTrace() or nil iа no errors with stack trace
func Stack(err error) errors.StackTrace {
type (
causer interface {
Cause() error
}
stackTracer interface {
StackTrace() errors.StackTrace
}
)
var stackErr error
for {
if _, ok := err.(stackTracer); ok {
stackErr = err
}
if causer, ok := err.(causer); ok {
err = causer.Cause()
} else {
break
}
}
if stackErr != nil {
return stackErr.(stackTracer).StackTrace()
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment