Go Reference ยท Concepts
Error handling conventions in Go
Go error conventions in one place: returning errors, wrapping with %w, sentinel errors, custom error types, errors.Is and errors.As, and what to put in messages.
In Go, an error is an ordinary value of the built-in interface error, which has one method, Error() string. A function that can fail returns an error as its last result, and the caller checks it right away. There are no exceptions to catch; the convention is explicit, local and visible in the code.
Good error handling is mostly about three choices: how you create an error, how you add context as it travels up the call stack, and how callers recognize a specific error. This page collects the conventions the standard library and most Go code follow.
f, err := os.Open(name) if err != nil { return fmt.Errorf("load config: %w", err) }
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.
The conventions
- Return, do not panic. Expected failures (bad input, missing file, network trouble) are errors. See Panic and recover rules.
- Check immediately, and keep the happy path unindented: handle
err != nilwith an early return. - Add context once per layer, saying what you were doing:
fmt.Errorf("read config: %w", err). Do not repeat the word "error" or "failed to"; the message chain readsread config: open app.toml: no such file or directory. - Wrap with
%wonly when callers may depend on the cause. Wrapping makes the inner error part of your API. Use%vto hide the detail. - Compare with
errors.Is, extract witherrors.As, never with==or type assertions on wrapped errors. - Use a sentinel (
var ErrX = errors.New(...)) when callers only need to know "which condition", and a custom type when they need data (field, code, retry-after). Name typesFooErrorand sentinelsErrFoo. - Messages are lowercase, without trailing punctuation, because they are concatenated.
- Handle an error once. Either log it or return it, not both; otherwise the same failure appears several times in the log.
Usage notes
- A method with a pointer receiver on an error type means
errors.Asneeds a pointer-to-pointer target (var ve *ValidationError; errors.As(err, &ve)). - Returning a nil
*MyErroras anerroryields a non-nil interface. Return a literalnilon success. errors.Joinand multiple%wverbs in onefmt.Errorf(Go 1.20+) make a tree of errors;IsandAssearch all branches.- Custom types can implement
Is(target error) boolorUnwrap() errorto customize matching. defer f.Close()ignores the close error. When it matters (writes), return it through a named result.