Documentation ¶
Overview ¶
werrors is a minimalistic package that providers only Wrap, Wrapf, WithMessage, WithMessagef, Cause and Into functions.
This allow use the standard "errors" package for New / Errorf, Is, As, etc.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Cause ¶
Cause returns the underlying cause of the error, if possible. An error value has a cause if it implements the following interface:
type causer interface { Cause() error }
If the error does not implement Cause, we will call Unwrap in a loop until find the original error. If the error is nil, nil will be returned without further investigation.
Example ¶
package main import ( "errors" "fmt" "github.com/peczenyj/errors/werrors" ) func fn() error { e1 := errors.New("error") e2 := werrors.Wrap(e1, "inner") e3 := werrors.Wrap(e2, "middle") return werrors.Wrap(e3, "outer") } func main() { err := fn() fmt.Println(err) fmt.Println(werrors.Cause(err)) }
Output: outer: middle: inner: error error
func Into ¶
Into finds the first error in err's chain that matches target type T, and if so, returns it.
Into is type-safe alternative to As.
Example ¶
package main import ( "errors" "fmt" "github.com/peczenyj/errors/werrors" ) type timeoutError struct { err error } func (te *timeoutError) Error() string { return "timeout: " + te.err.Error() } func (te *timeoutError) Timeout() bool { return true } type TimeoutError interface { Timeout() bool error } func main() { err := errors.New("ops") err = &timeoutError{err} err = werrors.Wrap(err, "unexpected") if terr, ok := werrors.Into[TimeoutError](err); ok { fmt.Println(terr) } }
Output: timeout: ops
func WithMessage ¶
WithMessage is an alias to Wrap.
Example ¶
package main import ( "errors" "fmt" "github.com/peczenyj/errors/werrors" ) func main() { cause := errors.New("whoops") err := werrors.WithMessage(cause, "oh noes") fmt.Println(err) }
Output: oh noes: whoops
func WithMessagef ¶
WithMessagef is an alias to Wrapf.
func Wrap ¶
Wrap returns an error annotating err, it is the equivalent to
fmt.Errorf("%s: %w", message, err)
If err is nil, Wrap returns nil.
Example ¶
package main import ( "errors" "fmt" "github.com/peczenyj/errors/werrors" ) func main() { cause := errors.New("whoops") err := werrors.Wrap(cause, "oh noes") fmt.Println(err) }
Output: oh noes: whoops
Types ¶
This section is empty.