78 lines
1.1 KiB
Go
78 lines
1.1 KiB
Go
package x
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"runtime"
|
|
)
|
|
|
|
func Assert(cond bool, msg string) {
|
|
if cond {
|
|
panic(errors.New(msg))
|
|
}
|
|
}
|
|
|
|
func Check(cond bool, err error) *invariants {
|
|
return new(invariants).Check(cond, err)
|
|
}
|
|
|
|
type invariants struct {
|
|
errs []error
|
|
}
|
|
|
|
func (i *invariants) Check(cond bool, err error) *invariants {
|
|
if !cond {
|
|
i.errs = append(i.errs, err)
|
|
}
|
|
return i
|
|
}
|
|
|
|
func (i *invariants) Join() error {
|
|
return errors.Join(i.errs...)
|
|
}
|
|
func (i *invariants) First() error {
|
|
if len(i.errs) > 0 {
|
|
return i.errs[0]
|
|
}
|
|
return nil
|
|
}
|
|
func (i *invariants) All() []error {
|
|
return i.errs
|
|
}
|
|
|
|
type xError struct {
|
|
LineNo int
|
|
File string
|
|
E error
|
|
Debug bool
|
|
}
|
|
|
|
func (e *xError) Error() string {
|
|
if e.Debug {
|
|
return fmt.Sprintf(
|
|
"%s\n\t%s:%d", e.E, e.File, e.LineNo,
|
|
)
|
|
}
|
|
return e.E.Error()
|
|
}
|
|
|
|
func (e *xError) Unwrap() error {
|
|
return e.E
|
|
}
|
|
|
|
func NewError(unwrapped error, debug bool) error {
|
|
_, file, line, ok := runtime.Caller(1)
|
|
|
|
if !ok {
|
|
file = "unknown"
|
|
line = 0
|
|
}
|
|
|
|
return &xError{
|
|
LineNo: line,
|
|
File: file,
|
|
E: unwrapped,
|
|
Debug: debug,
|
|
}
|
|
}
|