Added data to wrapped error

This commit is contained in:
Magnus Åhall 2023-09-26 09:31:18 +02:00
parent b77f5b94c8
commit 35249137c5

29
pkg.go
View File

@ -10,8 +10,9 @@ import (
type Error struct { type Error struct {
err error err error
file string File string
line int Line int
Data interface{}
} }
type LogCallback func(Error) type LogCallback func(Error)
@ -44,20 +45,21 @@ func callback(wrapped Error) {
func (wrapped Error) Error() string { func (wrapped Error) Error() string {
return fmt.Sprintf( return fmt.Sprintf(
"[%s:%d] %s", "[%s:%d] %s",
wrapped.file, wrapped.File,
wrapped.line, wrapped.Line,
wrapped.err.Error(), wrapped.err.Error(),
) )
} }
func create(err error) error { func create(err error, data interface{}) error {
_, file, line, _ := runtime.Caller(2) _, file, line, _ := runtime.Caller(2)
file = file[baseDirLength+1:] file = file[baseDirLength+1:]
wrapped := Error{ wrapped := Error{
err: err, err: err,
file: file, File: file,
line: line, Line: line,
Data: data,
} }
callback(wrapped) callback(wrapped)
@ -67,11 +69,20 @@ func create(err error) error {
// 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) return create(err, "")
}
func WrapData(err error, data interface{}) error {
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) error { func New(msg string) error {
wrapped := create(errors.New(msg)) wrapped := create(errors.New(msg), "")
return wrapped
}
func NewData(msg string, data interface{}) error {
wrapped := create(errors.New(msg), data)
return wrapped return wrapped
} }