2020-09-09 11:48:46 +02:00
|
|
|
package adverr
|
|
|
|
|
|
|
|
import "fmt"
|
|
|
|
|
|
|
|
var (
|
|
|
|
// ErrTmplUsedAsErr is returned from ErrTmpl.Error() because an error template should never be used as an actual error value
|
|
|
|
ErrTmplUsedAsErr = NewErrTmpl("ErrTmplUsedAsErr", "Error template used as error value: %s")
|
|
|
|
)
|
|
|
|
|
|
|
|
// ErrTmpl is an error template to define equalities between different errors
|
|
|
|
type ErrTmpl struct {
|
|
|
|
name string
|
|
|
|
format string
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewErrTmpl returns a new error template with the given format string as a predefined error message
|
|
|
|
func NewErrTmpl(name, format string) *ErrTmpl {
|
|
|
|
return &ErrTmpl{name, format}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error implementation just for satisfying the error interface
|
|
|
|
// Please dont use ErrTmpls as actual errors
|
|
|
|
func (t *ErrTmpl) Error() string {
|
|
|
|
return ErrTmplUsedAsErr.New(errtype(t)).Error()
|
|
|
|
}
|
|
|
|
|
|
|
|
// New returns a new Error in which the given values are being formatted into the format string of its template
|
|
|
|
func (t *ErrTmpl) New(args ...interface{}) *Error {
|
|
|
|
return &Error{
|
|
|
|
msg: fmt.Sprintf(t.format, args...),
|
|
|
|
cause: nil,
|
|
|
|
tmpl: t,
|
|
|
|
callTrace: Trace(2),
|
|
|
|
}
|
|
|
|
}
|
2020-09-09 14:06:31 +02:00
|
|
|
|
|
|
|
// Wrap returns a new Error with a given cause in which args are being formatted into the format string of its template
|
|
|
|
func (t *ErrTmpl) Wrap(cause error, args ...interface{}) *Error {
|
|
|
|
return &Error{
|
|
|
|
msg: fmt.Sprintf(t.format, args...),
|
|
|
|
cause: cause,
|
|
|
|
tmpl: t,
|
|
|
|
callTrace: Trace(2),
|
|
|
|
}
|
|
|
|
}
|
2021-09-09 16:35:48 +02:00
|
|
|
|
|
|
|
// Chain returns a new Error with the given message and a slice of errors
|
|
|
|
// which were caused in the same function in succession
|
|
|
|
func (t *ErrTmpl) Chain(msg string, errors []error) *Error {
|
|
|
|
return &Error{
|
|
|
|
msg: msg,
|
|
|
|
callTrace: Trace(2),
|
|
|
|
tmpl: t,
|
|
|
|
prev: errors,
|
|
|
|
}
|
|
|
|
}
|