agola/internal/errors/zerolog.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

64 lines
1.2 KiB
Go

package errors
import (
"encoding/json"
"fmt"
"strings"
)
// copied from zerolog console writer since they aren't exported
//nolint
const (
colorBlack = iota + 30
colorRed
colorGreen
colorYellow
colorBlue
colorMagenta
colorCyan
colorWhite
)
// colorize returns the string s wrapped in ANSI code c, unless disabled is true.
func colorize(s interface{}, c int, disabled bool) string {
if disabled {
return fmt.Sprintf("%s", s)
}
return fmt.Sprintf("\x1b[%dm%v\x1b[0m", c, s)
}
type errorFormat = struct {
Error string
Details []string
}
func FormatErrFieldValue(i interface{}) string {
switch d := i.(type) {
case []byte:
var ed errorFormat
if err := json.Unmarshal(d, &ed); err != nil {
return fmt.Sprintf("error: %v", err)
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("%s\n", ed.Error))
if len(ed.Details) > 0 {
sb.WriteString("error details:\n")
for _, l := range ed.Details {
sb.WriteString(fmt.Sprintf("%s\n", l))
}
}
return colorize(sb.String(), colorRed, false)
default:
return colorize(fmt.Sprintf("%s", d), colorRed, false)
}
}
func ErrorMarshalFunc(err error) interface{} {
ef := errorFormat{
Error: err.Error(),
Details: PrintErrorDetails(err),
}
return ef
}