Errors
15 steps in 6 sets of Go.
Go returns errors as values and the compiler will not let you forget one. The error interface, wrapping with %w, errors.Is and errors.As, your own error types, and defer, panic and recover.
The last set covers errors across goroutines, which is where it gets genuinely awkward. Fifteen steps, and you will type if err != nil more often than in any other tour on this site.
The error value
- error is an interfaceOne method, Error() string — anything with it is an error.
- ErrorsSentinel errors, custom types, and wrapping.
- The early returnHandle the error and return; the happy path stays at one indent.
Wrapping
- Wrapping with %wfmt.Errorf with %w adds context and keeps the original reachable.
- errors.IsComparing against a sentinel through any amount of wrapping.
- errors.AsRecovering the concrete error type, to read its fields.
- errors.JoinSeveral failures at once, in one error value.
Your own errors
- A custom error typeA struct error carries data, and can decide what it matches.
- The Must patternFor values that cannot fail at run time, panic at start-up instead.
defer, panic & recover
- defer and cleanupGuaranteed cleanup, and returning a deferred error.
- defer, preciselyDeferred calls run last-in-first-out, with arguments evaluated immediately.
- panic and recoverPanic is for the impossible; recover turns it back into an error at a boundary.
- Named resultsNaming the results lets a deferred function edit them on the way out.
Errors across goroutines
- Errors from goroutinesA goroutine cannot return, so the error travels on a channel.
Encore
- retry.goRetry with backoff, a context deadline, and errors that say what happened.