Coding/Learn/go/go error handling patterns
Go Foundational Course
01.Introduction, Toolchain & Package main
02.Variables, Zero Values, Constants & iota
03.Control Flow: If with Init Statements & Switch
04.The Unified For Loop & Range Iteration
05.Functions, Multiple Return Values & Named Returns
06.Arrays vs Slices: Dynamic Memory & Headers
07.Maps: Key-Value Hash Tables & Safe Access
08.Pointers & Value vs Pointer Semantics
09.Structs, Receiver Methods & Composition
10.Implicit Interfaces & Duck Typing with Typesafety
11.Explicit Error Handling, Wrapping & Inspection
12.Defer, Panic & Recover: Resource Cleanup
13.Strings, Runes & UTF-8 Encoding Internals
14.Goroutines & The M:N Work-Stealing Scheduler
15.Channels: CSP Concurrency & Pipelines
16.Select Statement, Non-Blocking IO & Timeouts
17.Mutexes, RWMutex & Atomic Primitives
18.Context Propagation, Cancellation & Deadlines
19.JSON Serialization, Tags & net/http Routing
20.Capstone: High-Performance Concurrent Microservice Engine
Course Certificate0%

Complete all lessons to earn

LearnExplicit Error Handling, Wrapping & Inspection
11 / 20 0%
Lesson 11 of 20
14 mins read

Explicit Error Handling, Wrapping & Inspection

PreviousNext Lesson
In Plain English

Go treats errors as regular values rather than hidden exceptions. Master returning (result, error), wrapping errors with fmt.Errorf("%w"), and inspecting error chains with errors.Is and errors.As.

The Mental Model

"Instead of an unexpected building fire alarm (exceptions), every room inspection produces a signed report card. If a defect is found, the inspector attaches a note and hands it up."

Deep Dive: How It Works

Errors as Values: error is a standard built-in interface with Error() string.

Explicit Handling: Errors are returned as the final return value and handled immediately with if err != nil.

Error Wrapping with %w: fmt.Errorf("ctx: %w", err) wraps errors so errors.Is and errors.As can unwrap them.

Syntax Blueprint

var ErrNotFound = errors.New("not found")
wrapped := fmt.Errorf("query failed: %w", ErrNotFound)
if errors.Is(wrapped, ErrNotFound) { ... }

Create sentinel errors, wrap with %w context, and inspect using errors.Is.

PointCore Rules to Remember

Point star
Explicit Values: No hidden exceptions; control flow is completely transparent and explicit.
Point star
Error Wrapping: Use fmt.Errorf with %w to maintain the full chain of error provenance.
Point star
Sentinel Inspection: Use errors.Is to inspect sentinel errors across nested wrapper layers.

Common Beginner Traps & How to Fix Them

Mistake:Using %v instead of %w when formatting errors with fmt.Errorf.

Why it happens: %v converts error to string, discarding the underlying error type chain needed for errors.Is.

How to fix: Always use %w when wrapping underlying errors.

Pro Tip: Define package-level sentinel errors (var ErrNotFound = errors.New(...)) so callers can test against them with errors.Is.

Live Interactive Example

Hit Run Code to see it live
Error Wrapping and Sentinel Inspection
Go 1.22 / Runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Output Console
Click "Run Code" to view the rendered output.
How it works: errors.Is walked the wrapped %w chain and matched ErrDatabaseOffline.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Safe Division with Custom Error

  • PointDefine a sentinel error var ErrDivideByZero = errors.New("cannot divide by zero").
  • PointWrite a function divide(a, b float64) (float64, error) that returns ErrDivideByZero if b == 0.
  • PointIn main(), call divide(10, 0), check if errors.Is(err, ErrDivideByZero), and print "Caught: divide by zero".
1
2
3
4
5
6
7
8
9
10
11
12
13
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates