Lab 04: Error Handling

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm golang:1.22-alpine sh

Overview

Go treats errors as values — they are returned from functions, not thrown. This makes error paths explicit and forces callers to handle them. The errors package and fmt.Errorf with %w provide a rich error wrapping and inspection system.

Step 1: The error Interface

error is a built-in interface with a single method:

type error interface {
    Error() string
}
package main

import (
    "errors"
    "fmt"
)

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 2)
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Printf("10 / 2 = %.1f\n", result)

    _, err = divide(5, 0)
    if err != nil {
        fmt.Println("error:", err)
    }
}

Step 2: Custom Error Types

Implement the error interface to carry structured context.

Step 3: Sentinel Errors

Predefined error values for comparison with errors.Is.

Step 4: Error Wrapping with %w

fmt.Errorf with %w wraps an error while preserving the original for errors.Is/errors.As.

💡 Tip: Use %w when callers need to inspect the cause. Use %v when you want to hide the original error type.

Step 5: errors.As — Type Assertion for Errors

errors.As traverses the error chain looking for a specific error type.

Step 6: panic and recover

panic stops normal execution. recover — called inside a defer — catches it.

💡 Tip: Use panic only for truly unrecoverable situations (programmer errors). For expected failures, return error.

Step 7: Multiple Error Returns & Error Aggregation

Step 8: Capstone — Layered Error Handling

📸 Verified Output:

Summary

Concept
API
When to Use

errors.New

Create simple error

Static error messages

fmt.Errorf("%w")

Wrap error with context

Add call-site info

errors.Is

Check error identity in chain

Sentinel error comparison

errors.As

Extract typed error from chain

Inspect structured error fields

errors.Unwrap

Get next error in chain

Manual chain traversal

panic/recover

Catch unrecoverable situations

Libraries preventing crashes

Sentinel errors

Package-level var Err... = errors.New(...)

Stable, comparable error values

Last updated