typestar

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.

Start this tour

The error value

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

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

Encore

  • retry.goRetry with backoff, a context deadline, and errors that say what happened.

The other Go tours