Skip to content
Justice Tech School

Errors In Practice

Return errors, add context with fmt.Errorf and %w, and handle them once at the right level. Never ignore an error silently. panic is for programmer mistakes.

Example
package main

import (
	"errors"
	"fmt"
	"os"
)

func readCfg(p string) error {
	_, err := os.ReadFile(p)
	if err != nil {
		return fmt.Errorf("read config: %w", err)
	}
	return nil
}

func main() {
	err := readCfg("/nonexistent/cfg.json")
	fmt.Println(err != nil, errors.Is(err, os.ErrNotExist))
}

Result

true true

Exercise

Wrap with context verb.

fmt.Errorf("x: ", err)

Quiz Test

What does %w do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.