Skip to content

Lesson 3 of 9 · 25m

Errors, Control Flow, and Failure Design

Design error sets, translation boundaries, cleanup paths, and user-facing failures without exceptions or hidden jumps.

Error handling is where many systems codebases quietly rot. The first prototype propagates every internal error, the CLI prints a library detail no user understands, and eventually nobody can tell which failures are expected operations and which are programming mistakes. Zig gives you a small set of tools — error unions, try, catch, defer, and errdefer — but it does not design your failure taxonomy for you.

Separate operational failure from programmer error

Operational failure is part of the environment: file missing, permission denied, malformed input, network unreachable. Programmer error is a violated invariant: impossible enum state, corrupted internal length, misuse of a private API. Conflating them produces defensive code everywhere and confidence nowhere.

const LoadError = error{
    FileTooLarge,
    InvalidUtf8,
    InvalidRecord,
} || std.fs.File.OpenError || std.fs.File.ReadError;

fn loadRecords(allocator: std.mem.Allocator, path: []const u8) LoadError![]Record {
    _ = allocator;
    _ = path;
    unreachable;
}

In real code, decide whether callers need the underlying file errors. Sometimes they do; sometimes the stable API should expose only error.ConfigUnreadable and log detail at the boundary.

Error translation is a security boundary too

Raw errors leak implementation shape. A CLI that prints error.FileNotFound for a supplied path is fine. A network service that reveals internal paths, SQL fragments, or backend topology is leaking operational detail. Translate at process or protocol boundaries:

fn run() !void {
    loadConfig() catch |err| switch (err) {
        error.FileNotFound => return report("config file not found"),
        error.AccessDenied => return report("config file is not readable"),
        else => return report("could not load configuration"),
    };
}

The internal error is not lost if you log it. The public contract remains stable.

errdefer is for partial construction

Any time initialization has stages, failure in stage three must undo stages one and two. That is what errdefer is for:

fn connectAll(allocator: std.mem.Allocator) !Resources {
    const a = try allocator.create(Service);
    errdefer allocator.destroy(a);

    a.* = try Service.init(allocator);
    errdefer a.deinit();

    const b = try Service.init(allocator);
    errdefer b.deinit();

    return .{ .first = a, .second = b };
}

The exact object layout will vary, but the principle does not: cleanup that runs only on failure belongs in errdefer; cleanup that always runs belongs in defer.

Do not use catch unreachable as a lifestyle

catch unreachable means "I believe this cannot fail." Sometimes that is true: formatting into a fixed buffer whose capacity you just proved sufficient. Often it means "I did not want to design the failure path." If the failure is environment-dependent, unreachable is a future crash.

Useful alternatives are explicit:

const value = parse(input) catch |err| switch (err) {
    error.InvalidCharacter => return error.InvalidRecord,
    error.Overflow => return error.ValueOutOfRange,
};

Yes, it is more typing. That typing is the design work.

Panic, abort, or continue deliberately

In library code, propagate errors. In a small CLI, it can be correct to print a concise diagnostic and exit nonzero. In a long-lived service, crashing on one malformed input may create a denial-of-service amplifier. There is no universal answer; there is only a failure policy.

CLI:       fail fast, concise stderr, nonzero exit
Library:   propagate typed errors, no process exit
Daemon:    isolate request failure, preserve service invariants
Embedded:  bounded recovery or controlled reset, never unbounded growth

Field notes

  • Error names are global within the error set namespace collision rules, not semantic documentation. error.Invalid means little without context.
  • Zig errors carry no payload. If users need line numbers or paths, carry diagnostics in a separate structure or report at the boundary.
  • try inside cleanup code is a warning sign; cleanup should usually be infallible or explicitly logged.
  • Do not enumerate impossible errors in public APIs merely to satisfy a compiler experiment. Re-evaluate whether the abstraction boundary is wrong.
  • Test failure paths with fault-injection allocators, missing files, malformed input, and short writes. Happy-path systems code is a demo, not a utility.

Was this lesson helpful?

Sign in to rate