Back to Concepts Roadmap
🟠 Level 2 β€” Flow Control
Flow Control

Error Handling

Master explicit error returns, custom error types, error wrapping with %w, and inspection with errors.Is and errors.As.

Real-World Analogy (Mental Model)

β€œImagine ordering a package online: instead of the delivery truck silently crashing (exceptions), the driver hands you two boxes at your door: your item, and a status sheet. If the status sheet says "Damaged in transit", you handle it right there.”

Architecture & Memory MapVisual Model
[Function Call] ──> Returns (Data, error)
                           β”‚
                           β”œβ”€β”€ If error != nil ──> Handle/Log/Wrap & Return
                           └── If error == nil ──> Proceed safely with Data

Key Concepts & Rules To Remember

  • Errors are normal values that implement the `error` interface (`Error() string`).
  • Functions return errors as the final return value: `result, err := doSomething()`.
  • Wrap errors with context using `fmt.Errorf("reading config failed: %w", err)`.
  • `errors.Is()` checks for specific sentinel errors, `errors.As()` extracts specific custom error types.
Step-by-Step Code

1. Idiomatic Error Returns and Wrapping

Go favors explicit, visible error handling over invisible exception bubbling:

example.goGo 1.24+
package main

import (
    "errors"
    "fmt"
)

var ErrUserNotFound = errors.New("user not found")

func findUser(id int) (string, error) {
    if id != 42 {
        return "", fmt.Errorf("lookup id %d: %w", id, ErrUserNotFound)
    }
    return "Alice", nil
}

func main() {
    _, err := findUser(99)
    if err != nil {
        if errors.Is(err, ErrUserNotFound) {
            fmt.Println("Handled missing user safely!")
        }
        fmt.Println("Full error chain:", err)
    }
}

Common Beginner Pitfalls & Mistakes

Mistake: Ignoring returned errors by assigning them to blank identifier `val, _ := compute()`.
βœ… Correct Way: Never discard errors in production code! Always check `if err != nil`.
Self Assessment

Knowledge Check

Verify your understanding with these interactive practice questions.

Quizzes

Quick checks for understanding

Multiple-choice with inline explanationsβ€”expand to see why.

Which formatting verb wraps an error so it can be unpacked by `errors.Is()`?

Finished this lesson?

Mark it as complete to track your overall Go mastery.