Skip to content
Guest
Go · Course Syllabus Show lessons
Types & Interfaces · 9 min read · Intermediate

Explicit Error Handling, Wrapping & Defer

Handle errors as explicit return values, wrap context with fmt.Errorf %w, inspect with errors.Is, and clean up with defer.

What you'll learn

  • Return and check error values idiomatically
  • Wrap errors with fmt.Errorf and %w
  • Guarantee resource cleanup with defer

Overview

Handle errors as explicit return values, wrap context with fmt.Errorf %w, inspect with errors.Is, and clean up with defer.

Go prioritizes simplicity, explicit control flow, fast compilation, and safe concurrency. Every feature in this lesson is part of Go’s minimal standard toolkit used across cloud infrastructure, CLI tools, and high-throughput APIs.

Idiomatic Go Example

package main

import (
    "errors"
    "fmt"
)

var ErrEmpty = errors.New("empty input")

func validate(s string) error {
    if s == "" {
        return fmt.Errorf("validate failed: %w", ErrEmpty)
    }
    return nil
}

Key Takeaways

  • Return and check error values idiomatically
  • Wrap errors with fmt.Errorf and %w
  • Guarantee resource cleanup with defer

Quick Check

Check Your Understanding

Score: 0 / 1

1. What does the `%w` verb in `fmt.Errorf` do?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind