niki/pkg/rich_error/rich_error.go

91 lines
1.2 KiB
Go
Raw Normal View History

2023-12-17 13:10:13 +00:00
package richerror
2024-01-01 07:22:14 +00:00
import "errors"
2023-12-17 13:10:13 +00:00
type Kind int
const (
KindInvalid Kind = iota + 1
KindForbidden
KindNotFound
KindUnexpected
)
type Op string
type RichError struct {
operation Op
wrappedError error
message string
kind Kind
meta map[string]interface{}
}
func New(op Op) RichError {
return RichError{operation: op}
}
func (r RichError) WithOp(op Op) RichError {
r.operation = op
2024-01-01 07:22:14 +00:00
2023-12-17 13:10:13 +00:00
return r
}
func (r RichError) WithErr(err error) RichError {
r.wrappedError = err
2024-01-01 07:22:14 +00:00
2023-12-17 13:10:13 +00:00
return r
}
func (r RichError) WithMessage(message string) RichError {
r.message = message
2024-01-01 07:22:14 +00:00
2023-12-17 13:10:13 +00:00
return r
}
func (r RichError) WithKind(kind Kind) RichError {
r.kind = kind
2024-01-01 07:22:14 +00:00
2023-12-17 13:10:13 +00:00
return r
}
func (r RichError) WithMeta(meta map[string]interface{}) RichError {
r.meta = meta
2024-01-01 07:22:14 +00:00
2023-12-17 13:10:13 +00:00
return r
}
func (r RichError) Error() string {
if r.message == "" {
return r.wrappedError.Error()
}
return r.message
}
func (r RichError) Kind() Kind {
if r.kind != 0 {
return r.kind
}
var re RichError
2024-01-01 08:31:10 +00:00
if !errors.As(r.wrappedError, &re) {
2023-12-17 13:10:13 +00:00
return 0
}
return re.Kind()
}
func (r RichError) Message() string {
if r.message != "" {
return r.message
}
var re RichError
2024-01-01 08:31:10 +00:00
if !errors.As(r.wrappedError, &re) {
2023-12-17 13:10:13 +00:00
return r.wrappedError.Error()
}
return re.Message()
}