This commit is contained in:
parent
8de3b04032
commit
f0fd3f8df1
25
pkg.go
25
pkg.go
@ -6,36 +6,54 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Assert evalueates a condition and if it fails, panics.
|
||||||
func Assert(cond bool, msg string) {
|
func Assert(cond bool, msg string) {
|
||||||
if cond {
|
if !cond {
|
||||||
panic(errors.New(msg))
|
panic(errors.New(msg))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Check(cond bool, err error) *invariants {
|
// Check evaluates a condition, adds an error to its list and continues
|
||||||
|
func Check(cond bool, err error) I {
|
||||||
return new(invariants).Check(cond, err)
|
return new(invariants).Check(cond, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// func ExampleCheck() {
|
||||||
|
|
||||||
|
// }
|
||||||
|
|
||||||
|
type I interface {
|
||||||
|
Check(cond bool, err error) I
|
||||||
|
Join() error
|
||||||
|
First() error
|
||||||
|
All() []error
|
||||||
|
}
|
||||||
type invariants struct {
|
type invariants struct {
|
||||||
errs []error
|
errs []error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *invariants) Check(cond bool, err error) *invariants {
|
// Check evaluates a condition, adds an error to its list and continues
|
||||||
|
func (i *invariants) Check(cond bool, err error) I {
|
||||||
if !cond {
|
if !cond {
|
||||||
i.errs = append(i.errs, err)
|
i.errs = append(i.errs, err)
|
||||||
}
|
}
|
||||||
return i
|
return i
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Join returns all an error wrapping all errors that have been seen by the checks
|
||||||
func (i *invariants) Join() error {
|
func (i *invariants) Join() error {
|
||||||
return errors.Join(i.errs...)
|
return errors.Join(i.errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// First returns the first error found by the checks
|
||||||
func (i *invariants) First() error {
|
func (i *invariants) First() error {
|
||||||
if len(i.errs) > 0 {
|
if len(i.errs) > 0 {
|
||||||
return i.errs[0]
|
return i.errs[0]
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// All returns all errors found by the checks as a list of errors
|
||||||
func (i *invariants) All() []error {
|
func (i *invariants) All() []error {
|
||||||
return i.errs
|
return i.errs
|
||||||
}
|
}
|
||||||
@ -60,6 +78,7 @@ func (e *xError) Unwrap() error {
|
|||||||
return e.E
|
return e.E
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewError return an error that wrapped an error and optionally provides the file and line number the error occured on
|
||||||
func NewError(unwrapped error, debug bool) error {
|
func NewError(unwrapped error, debug bool) error {
|
||||||
_, file, line, ok := runtime.Caller(1)
|
_, file, line, ok := runtime.Caller(1)
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user