jldb/lib/errs/error.go

120 lines
2.0 KiB
Go
Raw Permalink Normal View History

2023-10-13 09:43:27 +00:00
package errs
import (
"encoding/binary"
"fmt"
"io"
"runtime/debug"
)
type Error struct {
2023-12-05 10:24:03 +00:00
Code int64
Msg string
StackTrace string
2023-10-13 09:43:27 +00:00
collection string
index string
err error // Wrapped error
}
func NewErr(code int64, msg string) *Error {
return &Error{
2023-12-05 10:24:03 +00:00
Code: code,
Msg: msg,
2023-10-13 09:43:27 +00:00
}
}
func (e *Error) Error() string {
if e.collection != "" || e.index != "" {
2023-12-05 10:24:03 +00:00
return fmt.Sprintf(`[%d] (%s/%s) %s`, e.Code, e.collection, e.index, e.Msg)
2023-10-13 09:43:27 +00:00
} else {
2023-12-05 10:24:03 +00:00
return fmt.Sprintf("[%d] %s", e.Code, e.Msg)
2023-10-13 09:43:27 +00:00
}
}
func (e *Error) Is(rhs error) bool {
e2, ok := rhs.(*Error)
if !ok {
return false
}
2023-12-05 10:24:03 +00:00
return e.Code == e2.Code
}
func (e *Error) Unwrap() error {
return e.err
2023-10-13 09:43:27 +00:00
}
func (e *Error) WithErr(err error) *Error {
2023-12-05 10:24:03 +00:00
if e2, ok := err.(*Error); ok && e2.Code == e.Code {
2023-10-13 09:43:27 +00:00
return e2
}
e2 := e.WithMsg(err.Error())
e2.err = err
return e2
}
func (e *Error) WithMsg(msg string, args ...any) *Error {
err := *e
2023-12-05 10:24:03 +00:00
err.Msg += ": " + fmt.Sprintf(msg, args...)
if len(err.StackTrace) == 0 {
err.StackTrace = string(debug.Stack())
2023-10-13 09:43:27 +00:00
}
return &err
}
func (e *Error) WithCollection(s string) *Error {
err := *e
err.collection = s
return &err
}
func (e *Error) WithIndex(s string) *Error {
err := *e
err.index = s
return &err
}
func (e *Error) msgTruncacted() string {
2023-12-05 10:24:03 +00:00
if len(e.Msg) > 255 {
return e.Msg[:255]
2023-10-13 09:43:27 +00:00
}
2023-12-05 10:24:03 +00:00
return e.Msg
2023-10-13 09:43:27 +00:00
}
func (e *Error) Write(w io.Writer) error {
msg := e.msgTruncacted()
2023-12-05 10:24:03 +00:00
if err := binary.Write(w, binary.LittleEndian, e.Code); err != nil {
2023-10-13 09:43:27 +00:00
return IO.WithErr(err)
}
if _, err := w.Write([]byte{byte(len(msg))}); err != nil {
return err
}
_, err := w.Write([]byte(msg))
return err
}
func (e *Error) Read(r io.Reader) error {
var (
size uint8
)
2023-12-05 10:24:03 +00:00
if err := binary.Read(r, binary.LittleEndian, &e.Code); err != nil {
2023-10-13 09:43:27 +00:00
return IO.WithErr(err)
}
if err := binary.Read(r, binary.LittleEndian, &size); err != nil {
return IO.WithErr(err)
}
msgBuf := make([]byte, size)
if _, err := io.ReadFull(r, msgBuf); err != nil {
return IO.WithErr(err)
}
2023-12-05 10:24:03 +00:00
e.Msg = string(msgBuf)
2023-10-13 09:43:27 +00:00
return nil
}