agola/internal/errors/format.go
Simone Gotti d2b09d854f *: use new errors handling library
Implement a new error handling library based on pkg/errors. It provides
stack saving on wrapping and exports some function to add stack saving
also to external errors.
It also implements custom zerolog error formatting without adding too
much verbosity by just printing the chain error file:line without a full
stack trace of every error.

* Add a --detailed-errors options to print error with they full chain
* Wrap all error returns. Use errors.WithStack to wrap without adding a
  new messsage and error.Wrap[f] to add a message.
* Add golangci-lint wrapcheck to check that external packages errors are
  wrapped. This won't check that internal packages error are wrapped.
  But we want also to ensure this case so we'll have to find something
  else to check also these.
2022-02-28 12:49:13 +01:00

48 lines
912 B
Go

package errors
import (
"errors"
"fmt"
)
func PrintErrorDetails(err error) []string {
type stackTracer interface {
StackTrace() StackTrace
}
type errWithStack struct {
err error
msg string
stack StackTrace
}
var stackErrs []errWithStack
errCause := err
for errCause != nil {
stackErr := errWithStack{
err: errCause,
msg: errCause.Error(),
}
//nolint:errorlint
if s, ok := errCause.(stackTracer); ok {
stackErr.stack = s.StackTrace()
}
stackErrs = append(stackErrs, stackErr)
errCause = errors.Unwrap(errCause)
if err == nil {
break
}
}
var lines []string
for _, stackErr := range stackErrs {
if len(stackErr.stack) > 0 {
frame := stackErr.stack[0]
lines = append(lines, fmt.Sprintf("(%T) %+v: %s", stackErr.err, frame, stackErr.msg))
} else {
lines = append(lines, fmt.Sprintf("(%T) %s", stackErr.err, stackErr.msg))
}
}
return lines
}