Skip to main content
Module 10 · Lesson 2 of 547/50 in the course~14 min
Module lessons (2/5)

Idiomatic error handling

Lesson preview5 hands-on exercises readyCourse Go · Module 10 — Idiomatic practice

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.Join and confine panic/recover to 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

  1. 1Sentinel errors and errors.Is
  2. 2Typed errors and errors.As
  3. 3Context with %w and multiple errors with errors.Join
  4. 4When to use panic and recover
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 10 — Idiomatic practice

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.