Module lessons (2/5)
Idiomatic error handling
Sentinel errors (io.EOF), custom errors with Unwrap, wrapping with %w, when to use panic.
What you'll learn in this lesson
- Propagate errors by adding descriptive context and preserving the cause with
fmt.Errorf("...: %w", err). - Compare sentinel errors across the chain via
errors.Is. - Extract structured errors and custom metadata with
errors.As. - Combine multiple errors with
errors.Joinand confinepanic/recoverto unrecoverable cases only.
Overview
In Go, errors are normal values, not invisible exceptions. Handling them explicitly at the point of call allows you to add useful context to each layer and inspect the root cause in a typed way via the standard library errors.
A sentinel error is an exported global value (ErrNotFound, io.EOF, os.ErrNotExist). When traversing multiple levels of calls wrapped with %w, simple err == ErrNotFound would fail: always use errors.Is:
Sections covered in this lesson
- 1Sentinel errors and
errors.Is - 2Typed errors and
errors.As - 3Context with
%wand multiple errors witherrors.Join - 4When to use
panicandrecover - 5Guided practice
- 6Check for understanding
Unlock "Idiomatic error handling" and the full Course Go curriculum
Sentinel errors (`io.EOF`), custom errors with `Unwrap`, wrapping with `%w`, when to use `panic`.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.