Initial commit

This commit is contained in:
Magnus Åhall 2023-09-26 08:34:09 +02:00
commit 604df67596

72
pkg.go Normal file
View File

@ -0,0 +1,72 @@
package WrappedError
import (
// Standard
"errors"
"fmt"
"path"
"runtime"
)
type Error struct {
err error
file string
line int
}
type LogCallback func(Error)
var (
logCallback LogCallback
baseDirLength int
)
func init() {
_, file, _, _ := runtime.Caller(0)
dir := path.Dir(file)
dirBase := path.Dir(dir)
baseDirLength = len(dirBase)
}
func SetLogCallback(cbk LogCallback) {
logCallback = cbk
}
func callback(wrapped Error) {
if logCallback != nil {
logCallback(wrapped)
}
}
func (wrapped Error) Error() string {
return fmt.Sprintf(
"[%s:%d] %s",
wrapped.file,
wrapped.line,
wrapped.err.Error(),
)
}
func create(err error) error {
_, file, line, _ := runtime.Caller(2)
file = file[baseDirLength+1:]
wrapped := Error{
err: err,
file: file,
line: line,
}
callback(wrapped)
return wrapped
}
func Wrap(err error) error {
return create(err)
}
func New(msg string) error {
wrapped := create(errors.New(msg))
return wrapped
}