Documentation ¶
Overview ¶
Package errorx contains some error helpers
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Defer ¶
Defer is for use when defering a function call that can return an error. The error value of errp and the return value of f are joined with errors.Join.
Example ¶
Calling Close() on an io.WriteCloser can return an important error encountered while flushing to disk. Don't risk missing them by using a plain defer w.Close(). Use errorx.Defer to capture the return value.
package main import ( "fmt" "github.com/carlmjohnson/errorx" ) type closer struct{} func (c closer) Close() error { return fmt.Errorf("<had problem closing!>") } func openThingie() (c closer, err error) { return } // Calling Close() on an io.WriteCloser can return an important error // encountered while flushing to disk. Don't risk missing them by // using a plain defer w.Close(). Use errorx.Defer to capture the return value. func main() { // If you just defer a close call, you can miss an error return1 := func() error { thing, err := openThingie() if err != nil { return err } defer thing.Close() // oh no, this returned an error! // do stuff... return nil }() fmt.Println(return1) // == <nil> // Use errorx.Defer and a named return to capture the error return2 := func() (err error) { thing, err := openThingie() if err != nil { return err } defer errorx.Defer(&err, thing.Close) // do stuff... return nil }() fmt.Println(return2) // == <had problem closing!> }
Output: <nil> <had problem closing!>
func Recover ¶
func Recover(errp *error)
Recover catches any panics and converts them to errors when deferred.
Example ¶
package main import ( "fmt" "github.com/carlmjohnson/errorx" ) func main() { maybePanic := func(throws bool) (err error) { defer errorx.Recover(&err) if throws { panic("ahhh!") } return nil } err := maybePanic(false) fmt.Printf("error 1: %v\n", err) err = maybePanic(true) fmt.Printf("error 2: %v\n", err) }
Output: error 1: <nil> error 2: panic: ahhh!
func Trace ¶
func Trace(errp *error)
Trace joins the error with caller information if the error is not nil.
Example ¶
package main import ( "errors" "fmt" "github.com/carlmjohnson/errorx" ) func traceErr1(ok bool) (err error) { defer errorx.Trace(&err) if !ok { return errors.New("oh no!") } return nil } func traceErr2(x, y int) (err error) { defer errorx.Trace(&err) if x+y > 1 { return errors.New("uh oh!") } return nil } func main() { fmt.Println(traceErr1(true)) fmt.Println(traceErr1(false)) fmt.Println(traceErr2(1, -1)) fmt.Println(traceErr2(1, 1)) }
Output: <nil> @github.com/carlmjohnson/errorx_test.traceErr1 (trace_example_test.go:13) oh no! <nil> @github.com/carlmjohnson/errorx_test.traceErr2 (trace_example_test.go:21) uh oh!
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.