Documentation ¶
Overview ¶
Package errutil provides things for working with multiple errors and correctly handling errors from deferred calls.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Append ¶
Append creates an ErrorList. It is fine to call Append with any mix of nil, error, and Walker arguments. It will return nil, the only error passed in, or an ErrorList as appropriate. If the first non-nil argument is an ErrorList returned by this function, it may be modified. Append flattens its arguments.
func AppendCall ¶
AppendCall appends any error returned by the function to any existing errors. It is useful when returning an error from a deferred call.
WARNING: WHEN DOING THAT, MAKE SURE YOU PASS A POINTER TO A NAMED RETURN VALUE, ELSE THE RESULT WILL BE SILENTLY DISCARDED.
See silentlybroken_test.go for examples of the problem.
Example ¶
package main import ( "fmt" "io/ioutil" "os" "path/filepath" "sethwklein.net/go/errutil" ) func ReinventTheIOUtil(filename string) (buf []byte, err error) { f, err := os.Open(filename) if err != nil { return nil, err } defer errutil.AppendCall(&err, f.Close) buf, err = ioutil.ReadAll(f) if err != nil { return nil, err } return buf, nil } func main() { buf, err := ReinventTheIOUtil("errorlist.go") if err != nil { command := filepath.Base(os.Args[0]) errutil.Walk(err, func(e error) { fmt.Fprintf(os.Stderr, "%s, Error: %s\n", command, e) }) } _ = buf // do something magical with it! }
Output:
func Walk ¶
Walk does nothing if err is nil, calls ErrorList.Walk(walkFn) if err is a Walker, and calls walkFn(err) otherwise.
func WalkN ¶
WalkN visits at most the first n non-nil entries in err. It uses Walk.
Example ¶
package main import ( "fmt" "os" "sethwklein.net/go/errutil" ) func main() { var list error for i := 1; i <= 1000; i++ { list = errutil.Append(list, fmt.Errorf("number %v", i)) } errutil.WalkN(list, 3, func(e error) { // In real code, this should generally use os.Stderr, but // https://code.google.com/p/go/issues/detail?id=4550 // broke that for examples. fmt.Fprintln(os.Stdout, e) }) }
Output: number 1 number 2 number 3
Types ¶
type ErrorList ¶
type ErrorList interface { // Error is here to satisfy error and for callers who don't know this // might be a list. It probably doesn't give ideal results. Error() string // First returns the first error in the list. First() error // Walk is how callers who know this might be a list (possibly of lists) // print all the items. None of the errors passed to walkFn will be // an ErrorList. Walk(walkFn func(error)) }
ErrorList contains one or more errors. It's useful if you care about the errors from deferred calls or if you're processing several things and want to return more than just the first error encountered. The empty ErrorList is considered a pathological case and its behavior is undefined.