Select Git revision
hint.go 1.07 KiB
package errors
import (
"fmt"
"io"
)
type ErrHint interface{ Hint() string }
type withHint struct {
err error
hint string
}
func (w *withHint) Hint() string { return w.hint }
func (w *withHint) Error() string { return w.err.Error() }
func (w *withHint) Cause() error { return w.err }
func (w *withHint) Unwrap() error { return w.err }
func (w *withHint) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v", w.Cause())
fmt.Fprintf(s, "\nerror hint: %s", w.hint)
return
}
fallthrough
case 's':
io.WriteString(s, w.Error())
case 'q':
fmt.Fprintf(s, "%q", w.Error())
}
}
func WithHint(err error, hint string) error {
if err == nil {
return nil
}
return &withHint{err: err, hint: hint}
}
func WithHintf(err error, format string, args ...interface{}) error {
if err == nil {
return nil
}
return &withHint{err: err, hint: fmt.Sprintf(format, args...)}
}
func GetHint(err error) string {
for e := err; e != nil; e = Unwrap(e) {
if errDetail, ok := e.(ErrHint); ok {
return errDetail.Hint()
}
}
return ""
}