Skip to main content

Programming languages · Intermediate · 25 min

Handle errors the Go way: wrapping, errors.Is and errors.As

By Padding · Updated 18 Nov 2026
golang:1.27 (Debian) · Go 1.27.4

You will turn a Go 1.27 config loader that panics and returns bare errors into one whose errors carry context, can be matched with errors.Is and errors.As, report every problem at once, and map to the right HTTP status code.

On this page

In Go, an error is an ordinary value. Any type with an Error() string method satisfies the built-in error interface, and functions that can fail return one as their last result. There is no try and no exception that jumps over your code: the caller gets the error back and decides what to do with it. That makes failures visible, but it only helps if the errors say something useful and the caller can tell one kind of failure from another.

This tutorial starts from a small config loader that does neither. It panics when the file is missing and returns messages like invalid syntax with no file or line. Step by step you make its errors carry context, give callers stable values and types to check with errors.Is and errors.As, report every mistake in a file at once with errors.Join, and use panic only where it belongs. Last, you put the loader behind a small HTTP handler that turns each kind of error into the right status code, logs the detail and shows the client only what is safe.

Everything lives in ~/configload-demo, one Go module with a config package, a command-line checker and, later, a web server.

Step 1 · Start with a loader that panics

Create the project:

Bash
mkdir -p ~/configload-demo/config
cd ~/configload-demo
go mod init example.com/configload

The config format is one key = value per line, with # for comments. This first loader is the "before" version. Load panics on any problem, and Parse returns errors with no detail:

Bash
cat > config/config.go <<'GO'
package config

import (
	"errors"
	"os"
	"strconv"
	"strings"
	"time"
)

type Config struct {
	Name    string
	Port    int
	Timeout time.Duration
}

func Load(path string) Config {
	data, err := os.ReadFile(path)
	if err != nil {
		panic(err)
	}
	cfg, err := Parse(string(data))
	if err != nil {
		panic(err)
	}
	return cfg
}

func Parse(text string) (Config, error) {
	cfg := Config{Port: 8080, Timeout: 5 * time.Second}
	for _, line := range strings.Split(text, "\n") {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		key, value, found := strings.Cut(line, "=")
		if !found {
			return Config{}, errors.New("bad line")
		}
		key, value = strings.TrimSpace(key), strings.TrimSpace(value)
		switch key {
		case "name":
			cfg.Name = value
		case "port":
			port, err := strconv.Atoi(value)
			if err != nil {
				return Config{}, err
			}
			cfg.Port = port
		case "timeout":
			d, err := time.ParseDuration(value)
			if err != nil {
				return Config{}, err
			}
			cfg.Timeout = d
		default:
			return Config{}, errors.New("unknown key")
		}
	}
	if cfg.Name == "" {
		return Config{}, errors.New("missing name")
	}
	return cfg, nil
}
GO

The checker in the top folder loads a file named on the command line and prints what it found:

Bash
cat > main.go <<'GO'
package main

import (
	"fmt"
	"os"

	"example.com/configload/config"
)

func main() {
	path := "app.conf"
	if len(os.Args) > 1 {
		path = os.Args[1]
	}
	cfg := config.Load(path)
	fmt.Printf("loaded %s: port %d, timeout %s\n", cfg.Name, cfg.Port, cfg.Timeout)
}
GO

Add one good file and one with four mistakes: a port that is not a number, a misspelt key, a line with no =, and no name:

Bash
cat > good.conf <<'CONF'
# settings for the clinic booking API
name = clinic-api
port = 9000
timeout = 3s
CONF
cat > bad.conf <<'CONF'
# four mistakes
port = eighty
timeot = 3s
debug
CONF

Build it and try the good file, a file that does not exist and the bad file. The || echo part prints the exit status when the program fails:

Bash
gofmt -l .
go build -o bin/configcheck .
./bin/configcheck good.conf
./bin/configcheck nope.conf || echo "exit status $?"
./bin/configcheck bad.conf || echo "exit status $?"

Check it worked

The good file prints loaded clinic-api: port 9000, timeout 3s. The missing file prints panic: open nope.conf: no such file or directory, then a stack trace starting goroutine 1 [running]:, then exit status 2. The bad file panics too, with strconv.Atoi: parsing "eighty": invalid syntax: no file name, no line number, and only the first of the four mistakes. A user who sees that has to guess where to look. A missing config file is something that will happen on a fresh machine, and the program should not crash over it.

Step 2 · Return errors and add context with %w

The first fix is to stop panicking. Load returns (Config, error) like most Go functions that can fail, and each layer adds what it knows to the error before passing it up. fmt.Errorf with the %w verb builds a new error whose message is your context plus the original message, and which keeps the original inside it so callers can still inspect it later.

Two habits keep the messages readable. Say what the function was doing ("load config"), not "failed to" or "error:", since the reader already knows it is an error. And do not repeat what the inner error already says: the error from os.ReadFile already names the file, so Load adds the path only to parse errors. Go error strings start in lower case and have no full stop, because they usually end up in the middle of a longer message.

Split the package into two files. load.go holds Load and will not change again:

Bash
rm config/config.go
cat > config/load.go <<'GO'
package config

import (
	"fmt"
	"os"
	"time"
)

type Config struct {
	Name    string
	Port    int
	Timeout time.Duration
}

// Load reads and parses the config file at path.
func Load(path string) (Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return Config{}, fmt.Errorf("load config: %w", err)
	}
	cfg, err := Parse(string(data))
	if err != nil {
		return Config{}, fmt.Errorf("load config %s: %w", path, err)
	}
	return cfg, nil
}
GO

parse.go holds Parse, which now counts lines and puts the line number and key into every error:

Bash
cat > config/parse.go <<'GO'
package config

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"
)

// Parse reads key = value lines. Blank lines and lines starting with # are skipped.
func Parse(text string) (Config, error) {
	cfg := Config{Port: 8080, Timeout: 5 * time.Second}
	for i, line := range strings.Split(text, "\n") {
		n := i + 1
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		key, value, found := strings.Cut(line, "=")
		if !found {
			return Config{}, fmt.Errorf("line %d: expected key = value", n)
		}
		key, value = strings.TrimSpace(key), strings.TrimSpace(value)
		switch key {
		case "name":
			cfg.Name = value
		case "port":
			port, err := strconv.Atoi(value)
			if err != nil {
				return Config{}, fmt.Errorf("line %d: port: %w", n, err)
			}
			cfg.Port = port
		case "timeout":
			d, err := time.ParseDuration(value)
			if err != nil {
				return Config{}, fmt.Errorf("line %d: timeout: %w", n, err)
			}
			cfg.Timeout = d
		default:
			return Config{}, fmt.Errorf("line %d: unknown key %q", n, key)
		}
	}
	if cfg.Name == "" {
		return Config{}, errors.New("name is required")
	}
	return cfg, nil
}
GO

The checker handles the error itself: it prints the message to standard error and exits with status 1, which scripts read as "failed":

Bash
cat > main.go <<'GO'
package main

import (
	"fmt"
	"os"

	"example.com/configload/config"
)

func main() {
	path := "app.conf"
	if len(os.Args) > 1 {
		path = os.Args[1]
	}
	cfg, err := config.Load(path)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
	fmt.Printf("loaded %s: port %d, timeout %s\n", cfg.Name, cfg.Port, cfg.Timeout)
}
GO
gofmt -l .
go vet ./...
go build -o bin/configcheck .
./bin/configcheck good.conf
./bin/configcheck nope.conf || echo "exit status $?"
./bin/configcheck bad.conf || echo "exit status $?"

Check it worked

There is no stack trace any more. The two failures print:

Text
error: load config: open nope.conf: no such file or directory
exit status 1
error: load config bad.conf: line 2: port: strconv.Atoi: parsing "eighty": invalid syntax
exit status 1

Read the second line from left to right: each colon is one layer of the program adding what it knew. You can now find the mistake without opening the code.

Step 3 · Match failures with sentinel errors and errors.Is

Messages are for people. Code that needs to react to a particular failure must not compare message text, which changes whenever someone rewords it. Instead, a package declares sentinel errors: package-level values that callers compare against. The standard library has many, such as io.EOF and fs.ErrNotExist. (os.ErrNotExist is the same value as fs.ErrNotExist, so either name works.)

You cannot compare a wrapped error with ==, because the outer error is a new value. errors.Is(err, target) walks the chain that %w built, layer by layer, and reports whether target is anywhere in it.

Give the config package three sentinels in a new file:

Bash
cat > config/errors.go <<'GO'
package config

import "errors"

// Callers can test for these with errors.Is.
var (
	ErrMissingKey = errors.New("missing required key")
	ErrUnknownKey = errors.New("unknown key")
	ErrSyntax     = errors.New("expected key = value")
)
GO

Replace parse.go so that every failure wraps one of them, or the error from strconv or time:

Bash
cat > config/parse.go <<'GO'
package config

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

// Parse reads key = value lines. Blank lines and lines starting with # are skipped.
func Parse(text string) (Config, error) {
	cfg := Config{Port: 8080, Timeout: 5 * time.Second}
	for i, line := range strings.Split(text, "\n") {
		n := i + 1
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		key, value, found := strings.Cut(line, "=")
		if !found {
			return Config{}, fmt.Errorf("line %d: %w", n, ErrSyntax)
		}
		key, value = strings.TrimSpace(key), strings.TrimSpace(value)
		switch key {
		case "name":
			cfg.Name = value
		case "port":
			port, err := strconv.Atoi(value)
			if err != nil {
				return Config{}, fmt.Errorf("line %d: port: %w", n, err)
			}
			cfg.Port = port
		case "timeout":
			d, err := time.ParseDuration(value)
			if err != nil {
				return Config{}, fmt.Errorf("line %d: timeout: %w", n, err)
			}
			cfg.Timeout = d
		default:
			return Config{}, fmt.Errorf("line %d: %s: %w", n, key, ErrUnknownKey)
		}
	}
	if cfg.Name == "" {
		return Config{}, fmt.Errorf("name: %w", ErrMissingKey)
	}
	return cfg, nil
}
GO

Now the checker can treat a missing file differently from a broken one. A developer running it without a config should get working defaults; any other error still stops the program. That distinction is the point: a file that exists but cannot be read (wrong permissions, a disk fault) must not be quietly replaced by defaults, so the check is errors.Is(err, fs.ErrNotExist), not err != nil:

Bash
cat > main.go <<'GO'
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"time"

	"example.com/configload/config"
)

func main() {
	path := "app.conf"
	if len(os.Args) > 1 {
		path = os.Args[1]
	}
	cfg, err := config.Load(path)
	switch {
	case errors.Is(err, fs.ErrNotExist):
		fmt.Fprintf(os.Stderr, "note: %s not found, using development settings\n", path)
		cfg = config.Config{Name: "local-dev", Port: 8080, Timeout: 5 * time.Second}
	case err != nil:
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
	fmt.Printf("loaded %s: port %d, timeout %s\n", cfg.Name, cfg.Port, cfg.Timeout)
}
GO

Tests are where sentinels pay off, because they let you check the kind of failure without pinning the wording. The last test shows why the verb matters: %v prints the same text as %w but throws the original error away:

Bash
cat > config/errors_test.go <<'GO'
package config

import (
	"errors"
	"fmt"
	"io/fs"
	"path/filepath"
	"testing"
)

func TestLoadMissingFileIsNotExist(t *testing.T) {
	_, err := Load(filepath.Join(t.TempDir(), "nope.conf"))
	if !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("got %v, want an error wrapping fs.ErrNotExist", err)
	}
}

func TestParseSentinels(t *testing.T) {
	tests := []struct {
		name string
		text string
		want error
	}{
		{"no name", "port = 9000", ErrMissingKey},
		{"misspelt key", "name = x\ntimeot = 3s", ErrUnknownKey},
		{"no equals sign", "name = x\ndebug", ErrSyntax},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			_, err := Parse(tt.text)
			if !errors.Is(err, tt.want) {
				t.Errorf("Parse(%q) = %v, want an error wrapping %v", tt.text, err, tt.want)
			}
		})
	}
}

func TestPercentVHidesTheCause(t *testing.T) {
	wrapped := fmt.Errorf("load config: %w", fs.ErrNotExist)
	flattened := fmt.Errorf("load config: %v", fs.ErrNotExist)
	if wrapped.Error() != flattened.Error() {
		t.Fatalf("messages differ: %q and %q", wrapped, flattened)
	}
	if !errors.Is(wrapped, fs.ErrNotExist) {
		t.Error("the error built with w should still match fs.ErrNotExist")
	}
	if errors.Is(flattened, fs.ErrNotExist) {
		t.Error("the error built with v should not match fs.ErrNotExist")
	}
}
GO
gofmt -l .
go vet ./...
go test ./...
go build -o bin/configcheck .
./bin/configcheck nope.conf
./bin/configcheck bad.conf || echo "exit status $?"

Check it worked

go test ./... prints ok example.com/configload/config and ? example.com/configload [no test files] or similar. ./bin/configcheck nope.conf no longer fails: it prints note: nope.conf not found, using development settings and loaded local-dev: port 8080, timeout 5s, and exits with status 0. The bad file still stops with the same message as before.

Step 4 · Carry details in a custom error type and read them with errors.As

A sentinel answers "what kind of failure?" Sometimes the caller also needs data: which line, which key. Put that in a custom error type. It is a struct with an Error() method, and an Unwrap() method that returns the cause so errors.Is can still see through it:

Bash
cat > config/lineerror.go <<'GO'
package config

import "fmt"

// LineError is a problem in a config file. Line is 0 for problems that
// belong to the whole file, such as a missing key.
type LineError struct {
	Line int
	Key  string
	Err  error
}

func (e *LineError) Error() string {
	if e.Line == 0 {
		return fmt.Sprintf("%s: %v", e.Key, e.Err)
	}
	return fmt.Sprintf("line %d: %s: %v", e.Line, e.Key, e.Err)
}

func (e *LineError) Unwrap() error { return e.Err }
GO

Parse now returns a *LineError instead of building the message with fmt.Errorf. For a line with no =, the key is the whole line, so the user sees what was there:

Bash
cat > config/parse.go <<'GO'
package config

import (
	"strconv"
	"strings"
	"time"
)

// Parse reads key = value lines. Blank lines and lines starting with # are skipped.
func Parse(text string) (Config, error) {
	cfg := Config{Port: 8080, Timeout: 5 * time.Second}
	for i, line := range strings.Split(text, "\n") {
		n := i + 1
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		key, value, found := strings.Cut(line, "=")
		if !found {
			return Config{}, &LineError{Line: n, Key: line, Err: ErrSyntax}
		}
		key, value = strings.TrimSpace(key), strings.TrimSpace(value)
		switch key {
		case "name":
			cfg.Name = value
		case "port":
			port, err := strconv.Atoi(value)
			if err != nil {
				return Config{}, &LineError{Line: n, Key: key, Err: err}
			}
			cfg.Port = port
		case "timeout":
			d, err := time.ParseDuration(value)
			if err != nil {
				return Config{}, &LineError{Line: n, Key: key, Err: err}
			}
			cfg.Timeout = d
		default:
			return Config{}, &LineError{Line: n, Key: key, Err: ErrUnknownKey}
		}
	}
	if cfg.Name == "" {
		return Config{}, &LineError{Key: "name", Err: ErrMissingKey}
	}
	return cfg, nil
}
GO

errors.As is the type-based partner of errors.Is. It walks the same chain, and when it finds an error of the type you asked for, it stores it in your variable and returns true. You pass a pointer to a variable of that type. Because LineError has pointer methods, the variable is a *LineError and you pass &lineErr. Passing the wrong thing, such as a plain LineError value, makes errors.As panic; go vet catches that mistake for you.

Since Go 1.26 there is also the generic errors.AsType, which returns the value and a boolean and needs no variable declared beforehand. The checker uses it; the test below uses the classic form, so you have seen both:

Bash
cat > main.go <<'GO'
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"time"

	"example.com/configload/config"
)

func main() {
	path := "app.conf"
	if len(os.Args) > 1 {
		path = os.Args[1]
	}
	cfg, err := config.Load(path)
	switch {
	case errors.Is(err, fs.ErrNotExist):
		fmt.Fprintf(os.Stderr, "note: %s not found, using development settings\n", path)
		cfg = config.Config{Name: "local-dev", Port: 8080, Timeout: 5 * time.Second}
	case err != nil:
		fmt.Fprintln(os.Stderr, "error:", err)
		if lineErr, ok := errors.AsType[*config.LineError](err); ok && lineErr.Line > 0 {
			fmt.Fprintf(os.Stderr, "hint: open %s at line %d and check %q\n", path, lineErr.Line, lineErr.Key)
		}
		os.Exit(1)
	}
	fmt.Printf("loaded %s: port %d, timeout %s\n", cfg.Name, cfg.Port, cfg.Timeout)
}
GO
cat > config/lineerror_test.go <<'GO'
package config

import (
	"errors"
	"os"
	"path/filepath"
	"strconv"
	"testing"
)

func TestLoadBadPortGivesLineAndCause(t *testing.T) {
	path := filepath.Join(t.TempDir(), "app.conf")
	if err := os.WriteFile(path, []byte("name = x\nport = eighty\n"), 0o600); err != nil {
		t.Fatal(err)
	}
	_, err := Load(path)

	var lineErr *LineError
	if !errors.As(err, &lineErr) {
		t.Fatalf("got %v, want a *LineError in the chain", err)
	}
	if lineErr.Line != 2 || lineErr.Key != "port" {
		t.Errorf("got line %d key %q, want line 2 key %q", lineErr.Line, lineErr.Key, "port")
	}

	// The strconv error two layers down is still reachable.
	var numErr *strconv.NumError
	if !errors.As(err, &numErr) || numErr.Num != "eighty" {
		t.Errorf("got %v, want a *strconv.NumError for %q", err, "eighty")
	}
}
GO
gofmt -l .
go vet ./...
go test ./...
go build -o bin/configcheck .
./bin/configcheck bad.conf || echo "exit status $?"

Check it worked

go test ./... passes, including the three sentinel tests from the last step: Unwrap keeps errors.Is working through the new type. The bad file prints the same error line as before plus hint: open bad.conf at line 2 and check "port". The hint came from fields on the error, not from parsing its message.

Step 5 · Report every problem at once with errors.Join

bad.conf has four mistakes, and so far the user learns about them one at a time: fix, rerun, fix, rerun. errors.Join combines several errors into one. Its message is each message on its own line, and errors.Is and errors.As search every error inside it.

Replace parse.go so it collects problems instead of returning at the first one. errors.Join returns nil when it is given no errors (or only nil ones), so the end of the function needs no special case:

Bash
cat > config/parse.go <<'GO'
package config

import (
	"errors"
	"strconv"
	"strings"
	"time"
)

// Parse reads key = value lines. Blank lines and lines starting with # are skipped.
// It reports every problem it finds, joined into one error.
func Parse(text string) (Config, error) {
	cfg := Config{Port: 8080, Timeout: 5 * time.Second}
	var problems []error
	for i, line := range strings.Split(text, "\n") {
		n := i + 1
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		key, value, found := strings.Cut(line, "=")
		if !found {
			problems = append(problems, &LineError{Line: n, Key: line, Err: ErrSyntax})
			continue
		}
		key, value = strings.TrimSpace(key), strings.TrimSpace(value)
		switch key {
		case "name":
			cfg.Name = value
		case "port":
			port, err := strconv.Atoi(value)
			if err != nil {
				problems = append(problems, &LineError{Line: n, Key: key, Err: err})
				continue
			}
			cfg.Port = port
		case "timeout":
			d, err := time.ParseDuration(value)
			if err != nil {
				problems = append(problems, &LineError{Line: n, Key: key, Err: err})
				continue
			}
			cfg.Timeout = d
		default:
			problems = append(problems, &LineError{Line: n, Key: key, Err: ErrUnknownKey})
		}
	}
	if cfg.Name == "" {
		problems = append(problems, &LineError{Key: "name", Err: ErrMissingKey})
	}
	if err := errors.Join(problems...); err != nil {
		return Config{}, err
	}
	return cfg, nil
}
GO

errors.As stops at the first match, so it cannot list all four. The chain is really a tree: an error with Unwrap() error has one child, and one with Unwrap() []error (what errors.Join and fmt.Errorf with several %w verbs return) has many. A short function walks that tree and collects every *LineError:

Bash
cat > config/problems.go <<'GO'
package config

// Problems returns every *LineError inside err, in order.
func Problems(err error) []*LineError {
	var found []*LineError
	var walk func(error)
	walk = func(e error) {
		switch e := e.(type) {
		case *LineError:
			found = append(found, e)
		case interface{ Unwrap() []error }:
			for _, inner := range e.Unwrap() {
				walk(inner)
			}
		case interface{ Unwrap() error }:
			walk(e.Unwrap())
		}
	}
	walk(err)
	return found
}
GO

The checker prints the list. Errors that are not about the file's contents still print as one line:

Bash
cat > main.go <<'GO'
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"time"

	"example.com/configload/config"
)

func main() {
	path := "app.conf"
	if len(os.Args) > 1 {
		path = os.Args[1]
	}
	cfg, err := config.Load(path)
	switch {
	case errors.Is(err, fs.ErrNotExist):
		fmt.Fprintf(os.Stderr, "note: %s not found, using development settings\n", path)
		cfg = config.Config{Name: "local-dev", Port: 8080, Timeout: 5 * time.Second}
	case err != nil:
		problems := config.Problems(err)
		if len(problems) == 0 {
			fmt.Fprintln(os.Stderr, "error:", err)
			os.Exit(1)
		}
		fmt.Fprintf(os.Stderr, "%s is invalid:\n", path)
		for _, p := range problems {
			fmt.Fprintln(os.Stderr, "  "+p.Error())
		}
		os.Exit(1)
	}
	fmt.Printf("loaded %s: port %d, timeout %s\n", cfg.Name, cfg.Port, cfg.Timeout)
}
GO
cat > config/problems_test.go <<'GO'
package config

import (
	"errors"
	"strconv"
	"testing"
)

func TestParseReportsEveryProblem(t *testing.T) {
	_, err := Parse("port = eighty\ntimeot = 3s\ndebug\n")
	if got := len(Problems(err)); got != 4 {
		t.Fatalf("got %d problems, want 4: %v", got, err)
	}
	for _, target := range []error{ErrUnknownKey, ErrSyntax, ErrMissingKey} {
		if !errors.Is(err, target) {
			t.Errorf("errors.Is(err, %v) = false, want true", target)
		}
	}
	if _, ok := errors.AsType[*strconv.NumError](err); !ok {
		t.Error("want the *strconv.NumError for the port inside the joined error")
	}
}

func TestParseGoodTextHasNoProblems(t *testing.T) {
	cfg, err := Parse("name = clinic-api\nport = 9000\n")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if cfg.Port != 9000 || len(Problems(err)) != 0 {
		t.Errorf("got %+v with problems %v", cfg, Problems(err))
	}
}
GO
gofmt -l .
go vet ./...
go test ./...
go build -o bin/configcheck .
./bin/configcheck bad.conf || echo "exit status $?"

Check it worked

The tests pass, and the bad file now lists all four mistakes in one run:

Text
bad.conf is invalid:
  line 2: port: strconv.Atoi: parsing "eighty": invalid syntax
  line 3: timeot: unknown key
  line 4: debug: expected key = value
  name: missing required key
exit status 1

good.conf still loads. The earlier tests still pass too: errors.As in TestLoadBadPortGivesLineAndCause finds the first *LineError inside the joined error.

Step 6 · Keep panic for bugs, and recover only at a boundary

A panic stops the normal flow, runs deferred functions as it unwinds the stack, and crashes the program unless something calls recover. Use it when continuing would be wrong because the program itself is broken, not because the outside world misbehaved. A missing file, bad user input or a network timeout is an ordinary error. A value that your own code guarantees can never happen is a bug, and a panic with a stack trace is the fastest way to find it.

The standard library's pattern for this is a Must function, such as regexp.MustCompile. It is for input written into the program itself, where an error means the programmer made a mistake. Add one for config text in tests and examples:

Bash
cat > config/must.go <<'GO'
package config

import "fmt"

// MustParse is Parse for config text written into the program, such as
// test fixtures. It panics on error, because bad text there is a bug in the
// program, not a problem with anyone's input. Never use it on files or
// requests.
func MustParse(text string) Config {
	cfg, err := Parse(text)
	if err != nil {
		panic(fmt.Errorf("config.MustParse: %w", err))
	}
	return cfg
}
GO

recover only does something inside a deferred function, and only for a panic in the same goroutine. It returns the value passed to panic. A test is a good place to see it work:

Bash
cat > config/must_test.go <<'GO'
package config

import (
	"errors"
	"testing"
)

func TestMustParseGoodText(t *testing.T) {
	cfg := MustParse("name = fixture\n")
	if cfg.Name != "fixture" {
		t.Errorf("got name %q, want %q", cfg.Name, "fixture")
	}
}

func TestMustParsePanicsOnBadText(t *testing.T) {
	defer func() {
		err, ok := recover().(error)
		if !ok || !errors.Is(err, ErrMissingKey) {
			t.Fatalf("recovered %v, want an error wrapping ErrMissingKey", err)
		}
	}()
	MustParse("port = 9000")
	t.Error("MustParse returned instead of panicking")
}
GO
gofmt -l .
go vet ./...
go test -v -run 'MustParse' ./config

Do not use recover as a try and catch for ordinary errors. The one common place for it is the edge of a long-running program, such as an HTTP server, so that a bug in one request answers that request with a 500 instead of taking every other request down with it. You will write that next.

Check it worked

The output shows --- PASS: TestMustParseGoodText and --- PASS: TestMustParsePanicsOnBadText, then ok example.com/configload/config. The second test passed because the deferred function recovered the panic and found ErrMissingKey inside the panic value: the wrapping survives a panic too.

Step 7 · Map errors to HTTP status codes

Put the loader behind a small web server with one route, GET /configs/{name}, which loads configs/<name>.conf and returns it as JSON. Each kind of error gets its own status code:

  • The name has characters that are not allowed: 400 Bad Request. Checking it with a strict pattern also stops requests from reaching files outside configs/.
  • The file does not exist (errors.Is with fs.ErrNotExist): 404 Not Found.
  • The file has mistakes (config.Problems finds any): 422 Unprocessable Content, with the problems listed, since they are about the file the client asked for.
  • Anything else, from a disk fault to a bug: 500 Internal Server Error.

The split between what you log and what you show matters most for that last case. The full error may hold file paths, host names or other internals that help an attacker and confuse a user, so the server logs it in full and sends the client a short, fixed message. Client mistakes get at most a one-line info log, because they are not something an operator needs to fix.

Every response body has a stable code field next to the English message. A frontend can show its own text for each code, which makes it easy to show errors in French, Swahili or Yoruba without parsing English, and the bodies stay small for users on prepaid mobile data.

Bash
mkdir -p web configs
cat > web/main.go <<'GO'
package main

import (
	"encoding/json"
	"errors"
	"io/fs"
	"log/slog"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
	"runtime/debug"
	"time"

	"example.com/configload/config"
)

var validName = regexp.MustCompile(`^[a-z0-9-]{1,40}$`)

// apiError is what the client sees. Code is stable; Message is for people.
type apiError struct {
	Code     string   `json:"code"`
	Message  string   `json:"message"`
	Problems []string `json:"problems,omitempty"`
}

var internalError = apiError{Code: "internal", Message: "something went wrong on our side"}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	json.NewEncoder(w).Encode(v)
}

// classify picks the status code and the client-safe body for an error from config.Load.
func classify(err error) (int, apiError) {
	if errors.Is(err, fs.ErrNotExist) {
		return http.StatusNotFound, apiError{Code: "not_found", Message: "no config with that name"}
	}
	if problems := config.Problems(err); len(problems) > 0 {
		body := apiError{Code: "invalid_config", Message: "the config file has mistakes"}
		for _, p := range problems {
			body.Problems = append(body.Problems, p.Error())
		}
		return http.StatusUnprocessableEntity, body
	}
	return http.StatusInternalServerError, internalError
}

func showConfig(w http.ResponseWriter, r *http.Request) {
	name := r.PathValue("name")
	if !validName.MatchString(name) {
		writeJSON(w, http.StatusBadRequest, apiError{Code: "bad_name", Message: "config names use a-z, 0-9 and hyphens"})
		return
	}
	cfg, err := config.Load(filepath.Join("configs", name+".conf"))
	if err != nil {
		status, body := classify(err)
		if status >= 500 {
			slog.Error("load config", "name", name, "err", err)
		} else {
			slog.Info("config request refused", "name", name, "status", status)
		}
		writeJSON(w, status, body)
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"name":    cfg.Name,
		"port":    cfg.Port,
		"timeout": cfg.Timeout.String(),
	})
}

// recoverPanics turns a panic in a handler into a logged 500 for that request only.
func recoverPanics(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			v := recover()
			if v == nil {
				return
			}
			if v == http.ErrAbortHandler {
				panic(v) // net/http uses this panic on purpose; let it through
			}
			slog.Error("panic in handler", "path", r.URL.Path, "value", v, "stack", string(debug.Stack()))
			writeJSON(w, http.StatusInternalServerError, internalError)
		}()
		next.ServeHTTP(w, r)
	})
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /configs/{name}", showConfig)
	srv := &http.Server{
		Addr:              "127.0.0.1:8092",
		Handler:           recoverPanics(mux),
		ReadHeaderTimeout: 5 * time.Second,
	}
	slog.Info("listening", "addr", srv.Addr)
	if err := srv.ListenAndServe(); err != nil {
		slog.Error("server stopped", "err", err)
		os.Exit(1)
	}
}
GO

Go's HTTP server already recovers a panicking handler, but it only logs the panic and closes the connection, so the client gets no response at all. The middleware sends a proper 500 with the same body as any other internal error. Test both the mapping and the middleware without starting a server, using net/http/httptest:

Bash
cat > web/main_test.go <<'GO'
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"example.com/configload/config"
)

func TestClassify(t *testing.T) {
	tests := []struct {
		name string
		err  error
		want int
	}{
		{"missing file", fmt.Errorf("load config: %w", fs.ErrNotExist), http.StatusNotFound},
		{"bad contents", fmt.Errorf("load config x.conf: %w", errors.Join(&config.LineError{Line: 2, Key: "port", Err: config.ErrSyntax})), http.StatusUnprocessableEntity},
		{"anything else", errors.New("read configs/x.conf: input/output error"), http.StatusInternalServerError},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got, _ := classify(tt.err); got != tt.want {
				t.Errorf("classify(%v) = %d, want %d", tt.err, got, tt.want)
			}
		})
	}
}

func TestRecoverPanicsAnswers500(t *testing.T) {
	h := recoverPanics(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var counts map[string]int
		counts["boom"]++ // writing to a nil map panics
	}))
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/configs/clinic", nil))

	if rec.Code != http.StatusInternalServerError {
		t.Fatalf("got status %d, want 500", rec.Code)
	}
	body := rec.Body.String()
	if !strings.Contains(body, `"code":"internal"`) {
		t.Errorf("got body %s, want the internal error code", body)
	}
	if strings.Contains(body, "nil map") {
		t.Errorf("the panic text leaked to the client: %s", body)
	}
}
GO
gofmt -l .
go vet ./...
go test ./...

Now add four config files for the server: a good one, one with mistakes, and a directory where a file should be. Reading a directory fails with an error that is neither "not found" nor a mistake in the contents, so it stands in for the faults that are your side's problem, such as a failing disk or wrong permissions:

Bash
cp good.conf configs/clinic.conf
cp bad.conf configs/broken.conf
mkdir configs/legacy.conf
go build -o bin/configsrv ./web
./bin/configsrv 2> server.log &

The server's log goes to server.log so that your terminal stays free for curl.

Ask for each case. -w prints the status code on its own line after the body:

Bash
curl -s -w '%{http_code}\n' http://127.0.0.1:8092/configs/clinic
curl -s -w '%{http_code}\n' http://127.0.0.1:8092/configs/broken
curl -s -w '%{http_code}\n' http://127.0.0.1:8092/configs/nothing-here
curl -s -w '%{http_code}\n' http://127.0.0.1:8092/configs/Bad_Name
curl -s -w '%{http_code}\n' http://127.0.0.1:8092/configs/legacy
cat server.log

Check it worked

The five requests answer 200, 422, 404, 400 and 500, each on the line after its JSON body. The clinic body is {"name":"clinic-api","port":9000,"timeout":"3s"}. The broken body has "code":"invalid_config" and a problems list with the same four lines the checker printed. The legacy body is only {"code":"internal","message":"something went wrong on our side"}. In server.log, that request has an ERROR line with the real cause, something like err="load config: read configs/legacy.conf: is a directory", while the 404 and 422 requests have short INFO lines with their status. The 400 is rejected before any loading, so it logs nothing. go test ./... passed both packages, so the middleware answers a panic with a 500 and keeps the panic text out of the response.

Step 8 · Clean up

Stop the server and remove the project folder. kill %1 works in the terminal where you started the server with &; if you ran it in the foreground, press Ctrl+C there instead. Go stays installed:

Bash
kill %1
wait || true
cd ~
rm -rf ~/configload-demo

Check it worked

curl -s http://127.0.0.1:8092/configs/clinic now fails with a connection error and prints nothing, and ls ~/configload-demo says there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.