wrappederror/pkg.go

89 lines
1.6 KiB
Go
Raw Permalink Normal View History

2023-09-26 08:34:09 +02:00
package WrappedError
import (
// Standard
"errors"
"fmt"
"path"
"runtime"
)
type Error struct {
2023-09-26 09:33:46 +02:00
Wrapped error
2023-09-26 09:31:18 +02:00
File string
Line int
Data interface{}
2023-09-26 08:34:09 +02:00
}
type LogCallback func(Error)
var (
logCallback LogCallback
baseDirLength int
)
2023-09-26 09:17:17 +02:00
// Init only works if called from the main package and sets the length of code base path
// to later be removed in file paths to receive relative paths.
2023-09-26 09:11:10 +02:00
func Init() {
_, file, _, _ := runtime.Caller(1)
2023-09-26 09:12:57 +02:00
dirBase := path.Dir(file)
2023-09-26 08:34:09 +02:00
baseDirLength = len(dirBase)
}
2023-09-26 09:17:17 +02:00
// SetLogCallback gives a possibility to automatically run code to handle any errors.
2023-09-26 08:34:09 +02:00
func SetLogCallback(cbk LogCallback) {
logCallback = cbk
}
func callback(wrapped Error) {
if logCallback != nil {
logCallback(wrapped)
}
}
2023-09-26 09:17:17 +02:00
// Error implements the error inteface and adds filename and line to the error.
2023-09-26 08:34:09 +02:00
func (wrapped Error) Error() string {
return fmt.Sprintf(
"[%s:%d] %s",
2023-09-26 09:31:18 +02:00
wrapped.File,
wrapped.Line,
2023-09-26 09:33:46 +02:00
wrapped.Wrapped.Error(),
2023-09-26 08:34:09 +02:00
)
}
2023-09-26 09:31:18 +02:00
func create(err error, data interface{}) error {
2023-09-26 08:34:09 +02:00
_, file, line, _ := runtime.Caller(2)
file = file[baseDirLength+1:]
wrapped := Error{
2023-09-26 09:33:46 +02:00
Wrapped: err,
2023-09-26 09:31:18 +02:00
File: file,
Line: line,
Data: data,
2023-09-26 08:34:09 +02:00
}
callback(wrapped)
return wrapped
}
2023-09-26 09:17:17 +02:00
// Wrap wraps an existing error with file and line.
2023-09-26 08:34:09 +02:00
func Wrap(err error) error {
2023-09-26 09:31:18 +02:00
return create(err, "")
}
func WrapData(err error, data interface{}) error {
return create(err, data)
2023-09-26 08:34:09 +02:00
}
2023-09-26 09:17:17 +02:00
// New creates a new wrapped error with file and line.
2023-09-26 08:34:09 +02:00
func New(msg string) error {
2023-09-26 09:31:18 +02:00
wrapped := create(errors.New(msg), "")
return wrapped
}
func NewData(msg string, data interface{}) error {
wrapped := create(errors.New(msg), data)
2023-09-26 08:34:09 +02:00
return wrapped
}