Go Reference ยท Errors, I/O and Files
Go errors.Join() function
Reference for Go errors.Join (Go 1.20+): combine several errors into one, how nil values are dropped, the newline-separated message and matching with Is and As.
errors.Join(errs...) wraps several errors into a single one. It is made for code that keeps going after a failure and wants to report everything that went wrong: validating a form, closing several resources, or running tasks in a loop.
Nil arguments are discarded. If every argument is nil, Join returns nil, so you can pass the result of each step straight in and return it at the end. The message of the joined error is the messages of the parts, separated by newlines.
err := errors.Join(validateName(u), validateEmail(u), validateAge(u))
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Join(errs ...error) error
| Name | Description |
|---|---|
errs |
Any number of errors. Nil values are skipped. |
Returns: nil if there is no non-nil error; otherwise an error whose Error() joins the messages with newlines and whose Unwrap() []error method returns the non-nil errors.
Edge cases: the order of the arguments is kept. Joining an already joined error nests it, and Is / As search through every level.
Usage notes
IsandAslook at every part.errors.Is(joined, ErrName)is true if any of the joined errors is or wrapsErrName.errors.Unwrapreturns nil for joined errors, because they unwrap to a list. Use a type assertion tointerface{ Unwrap() []error }to get the parts.- The message has newlines. That suits logs and terminals, but it can be awkward in one-line JSON logs; build your own text from the parts if you need a different format.
- Pattern for cleanup:
err = errors.Join(err, f.Close())in a deferred function reports both the main error and the close error. - Not a substitute for context. Wrap each part with
fmt.Errorf("field %s: %w", ...)first if the reader needs to know where each failure came from. - Alternative with
fmt.Errorf: several%wverbs in one call also create a multi-error, with your own wording and separators. - Go 1.20 or later is required.