✨ Add errors.Errorf
This commit is contained in:
parent
59b2969d77
commit
6e7400df4d
5 changed files with 160 additions and 0 deletions
61
errorf.go
Normal file
61
errorf.go
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
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
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue