responsable-errors/errorf.go
2024-01-17 10:58:39 -06:00

61 lines
1.2 KiB
Go

package errors
import "fmt"
// Returns a ResponsableError formatted from the message, with the specified status.
// Errorf passes the heavy lifting off to fmt.Errorf, and returns a similar error.
// If one error is passed in the format, this will return an UnwrappableError.
// If more than one error is passed in the format, this will return an UnwrappableErrors.
func Errorf(status int, format string, parts ...any) ResponsableError {
err := fmt.Errorf(format, parts...)
msg := err.Error()
er := &erf{status, msg}
if we, ok := err.(wrappedError); ok {
return &wrapErr{er, we.Unwrap()}
}
if wes, ok := err.(wrappedErrors); ok {
return &wrapErrs{er, wes.Unwrap()}
}
return er
}
var _ ResponsableError = new(erf)
type erf struct {
stat int
msg string
}
func (e *erf) Status() int {
return e.stat
}
func (e *erf) Error() string {
return e.msg
}
func (e *erf) Msg() string {
return e.msg
}
var _ UnwrappableError = new(wrapErr)
type wrapErr struct {
*erf
err error
}
func (e *wrapErr) Unwrap() error {
return e.err
}
var _ UnwrappableErrors = new(wrapErrs)
type wrapErrs struct {
*erf
errs []error
}
func (e *wrapErrs) Unwrap() []error {
return e.errs
}