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

The error interface

Lesson preview5 hands-on exercises readyCourse Go · Module 6 — Interfaces

error is just Error() string; create custom errors, errors.Is, errors.As, fmt.Errorf("%w", err).

What you'll learn in this lesson

  • Define custom error-types by implementing Error() string on structs with contextual fields.
  • Distinguish between sentinel errors checked with errors.Is and custom error types extracted with errors.As.
  • Propagate the intact causal chain using fmt.Errorf("...: %w", err) instead of %v.

Overview

In the Go runtime error is simply a single-method built-in interface:

In addition to fmt.Errorf("...: %w", err), your error struct can also expose Unwrap() error to keep the entire chain compatible with errors.Is:

Sections covered in this lesson

  1. 1Sentinel errors vs custom struct errors
  2. 2errors.Is vs errors.As through %w chains
  3. 3Method Unwrap() error in custom errors
  4. 4Sentinel error vs textual comparison
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 6 — Interfaces

Unlock "The error interface" and the full Course Go curriculum

`error` is just `Error() string`; create custom errors, `errors.Is`, `errors.As`, `fmt.Errorf("%w", err)`.

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.