Added error codes

This commit is contained in:
Magnus Åhall 2024-03-29 11:14:01 +01:00
parent 16d41de1ae
commit bc020b2830

41
pkg.go
View File

@ -10,9 +10,16 @@ import (
type Error struct { type Error struct {
Wrapped error Wrapped error
ErrStr string // wrapped error isn't necessarily json encodable ErrStr string // wrapped error isn't necessarily json encodable
Code string `json:",omitempty"`
File string File string
Line int Line int
Data interface{} `json:",omitempty"` Data any `json:",omitempty"`
}
type CodableError interface {
error
WithCode(string) CodableError
WithData(any) CodableError
} }
type LogCallback func(Error) type LogCallback func(Error)
@ -43,15 +50,20 @@ func callback(wrapped Error) {
// Error implements the error inteface and adds filename and line to the error. // Error implements the error inteface and adds filename and line to the error.
func (wrapped Error) Error() string { func (wrapped Error) Error() string {
var code string
if wrapped.Code != "" {
code = wrapped.Code + " "
}
return fmt.Sprintf( return fmt.Sprintf(
"[%s:%d] %s", "%s[%s:%d] %s",
code,
wrapped.File, wrapped.File,
wrapped.Line, wrapped.Line,
wrapped.Wrapped.Error(), wrapped.Wrapped.Error(),
) )
} }
func create(err error, data interface{}) error { func create(err error, data interface{}) *Error {
if err == nil { if err == nil {
return nil return nil
} }
@ -67,27 +79,38 @@ func create(err error, data interface{}) error {
} }
callback(wrapped) callback(wrapped)
return wrapped return &wrapped
} }
// Wrap wraps an existing error with file and line. // Wrap wraps an existing error with file and line.
func Wrap(err error) error { func Wrap(err error) *Error {
return create(err, nil) return create(err, nil)
} }
func WrapData(err error, data interface{}) error { func WrapData(err error, data interface{}) *Error {
return create(err, data) return create(err, data)
} }
// New creates a new wrapped error with file and line. // New creates a new wrapped error with file and line.
func New(msg string, params ...any) error { func New(msg string, params ...any) *Error {
err := fmt.Errorf(msg, params...) err := fmt.Errorf(msg, params...)
wrapped := create(err, "") wrapped := create(err, nil)
return wrapped return wrapped
} }
func NewData(msg string, data interface{}, params ...any) error { // NewData creates a new WrappedError with associated data.
func NewData(msg string, data interface{}, params ...any) *Error {
err := fmt.Errorf(msg, params...) err := fmt.Errorf(msg, params...)
wrapped := create(err, data) wrapped := create(err, data)
return wrapped return wrapped
} }
func (e *Error) WithCode(code string) CodableError {
e.Code = code
return e
}
func (e *Error) WithData(data any) CodableError {
e.Data = data
return e
}