Skip to content

Zig Custom Error Sets

You now know how to return, pass on and handle errors. This last lesson in the section is about designing them: how to name your own error sets, how sets combine as errors move up through your program, when to let Zig infer a set and when to write it out, and what to do when an error name alone isn’t enough. That last one comes up quickly in real programs, because a message like “BadNumber” is a lot more helpful with “on line 3” next to it.

A good error set describes what can go wrong in one area of your program, using names that make sense to the caller. Here’s a set for reading a settings file:

const std = @import("std");
const ConfigError = error{
MissingEquals,
EmptyKey,
BadNumber,
};
fn parseValue(line: []const u8) ConfigError!u32 {
const eq = std.mem.findScalar(u8, line, '=') orelse return error.MissingEquals;
if (eq == 0) return error.EmptyKey;
return std.fmt.parseInt(u32, line[eq + 1 ..], 10) catch error.BadNumber;
}
pub fn main() void {
const lines = [_][]const u8{ "width=80", "height", "=24", "depth=lots" };
for (lines) |line| {
std.debug.print("{s}: {!d}\n", .{ line, parseValue(line) });
}
}

Output:

width=80: 80
height: error.MissingEquals
=24: error.EmptyKey
depth=lots: error.BadNumber

A few habits that make error sets pleasant to work with:

  • Name what went wrong, not where. BadNumber tells the caller something; ParseLineFailed doesn’t.
  • Translate low-level errors. parseInt can fail with InvalidCharacter or Overflow, but for a settings file both mean “that’s not a valid number”, so catch error.BadNumber turns them into one error that fits this set.
  • Keep sets small. If a set grows to twenty errors, it’s usually describing several jobs at once.

std.mem.findScalar returns the position of =, or null if there isn’t one, which orelse turns into an error (see Zig Optionals).

As errors travel up, a function often fails for reasons from several areas. || combines two error sets into one that contains every error from both:

const std = @import("std");
const ReadError = error{ FileNotFound, AccessDenied };
const ParseError = error{ MissingPort, BadNumber };
const LoadError = ReadError || ParseError;
fn readFile(name: []const u8) ReadError![]const u8 {
if (std.mem.eql(u8, name, "app.txt")) return "port=8080";
if (std.mem.eql(u8, name, "broken.txt")) return "port=80x";
if (std.mem.eql(u8, name, "secret.txt")) return error.AccessDenied;
return error.FileNotFound;
}
fn parsePort(text: []const u8) ParseError!u16 {
const value = std.mem.cutPrefix(u8, text, "port=") orelse return error.MissingPort;
return std.fmt.parseInt(u16, value, 10) catch error.BadNumber;
}
fn loadPort(name: []const u8) LoadError!u16 {
const text = try readFile(name);
return try parsePort(text);
}
pub fn main() void {
const names = [_][]const u8{ "app.txt", "broken.txt", "secret.txt", "other.txt" };
for (names) |name| {
std.debug.print("{s}: {!d}\n", .{ name, loadPort(name) });
}
std.debug.print("{s}\n", .{@typeName(LoadError)});
}

Output:

app.txt: 8080
broken.txt: error.BadNumber
secret.txt: error.AccessDenied
other.txt: error.FileNotFound
error{AccessDenied,BadNumber,FileNotFound,MissingPort}

loadPort can fail in all four ways, and its type says so. The two trys work because a ReadError or a ParseError fits into the bigger LoadError: a smaller set always coerces into a bigger one that contains all its errors. (std.mem.cutPrefix returns the rest of the text after "port=", or null if it doesn’t start with that.)

The other direction doesn’t work. You can’t pass a LoadError where only a ParseError is allowed, because it might be FileNotFound:

const ParseError = error{ MissingPort, BadNumber };
const ReadError = error{ FileNotFound, BadNumber };
const LoadError = ParseError || ReadError;
fn narrow(e: LoadError) ParseError {
return e;
}
pub fn main() void {
_ = narrow(error.BadNumber);
}
main.zig:6:12: error: expected type 'error{BadNumber,MissingPort}', found 'error{BadNumber,FileNotFound,MissingPort}'
return e;
^
main.zig:6:12: note: 'error.FileNotFound' not a member of destination error set

Also notice that both sets have BadNumber, and the merged set has it only once. Error names are global in Zig: error.BadNumber is the same value everywhere, so merging simply joins the lists.

The standard library’s error sets have names too, so you can merge them with yours. Any function that allocates can fail with error.OutOfMemory, which lives in std.mem.Allocator.Error:

const std = @import("std");
const MakeError = std.mem.Allocator.Error || error{EmptyName};
fn makeGreeting(gpa: std.mem.Allocator, name: []const u8) MakeError![]u8 {
if (name.len == 0) return error.EmptyName;
return gpa.print("Hello, {s}!", .{name});
}
pub fn main(init: std.process.Init) void {
const names = [_][]const u8{ "Ada", "" };
for (names) |name| {
const text = makeGreeting(init.gpa, name) catch |err| switch (err) {
error.EmptyName => {
std.debug.print("(no name given)\n", .{});
continue;
},
error.OutOfMemory => {
std.debug.print("out of memory\n", .{});
return;
},
};
defer init.gpa.free(text);
std.debug.print("{s}\n", .{text});
}
}

Output:

Hello, Ada!
(no name given)

Because MakeError is an exact set, the switch in main lists both errors and needs no else. If you later add error.NameTooLong to MakeError, the compiler shows you this switch, and every other place that needs updating. The language reference on merging error sets shows the same idea.

With !T, Zig works out the set for you. With ConfigError!T, you write it yourself. Both are fine, and real Zig code uses both. Here’s a rule of thumb:

Use !T (inferred) Use a named set
Small private helpers Functions other files or people call (pub fn)
Code that’s still changing a lot When callers should switch on every error
main and quick programs Recursive functions that handle their own errors

A named set is documentation the compiler checks. Someone reading fn loadPort(name: []const u8) LoadError!u16 knows exactly what can go wrong without reading the body. And as Zig Errors showed, a typo like error.NotFond is caught instead of becoming a new error.

That last row of the table is a real limit. The language reference on inferred error sets says they don’t mix well with recursion. Here’s what that looks like: this function counts opening brackets, calling itself on the rest of the text, and switches on its own errors:

const std = @import("std");
fn depth(text: []const u8) !u32 {
if (text.len == 0) return 0;
if (text[0] != '(') return error.NotABracket;
const inner = depth(text[1..]) catch |err| switch (err) {
error.NotABracket => return err,
};
return inner + 1;
}
pub fn main() void {
std.debug.print("{!d}\n", .{depth("(((")});
}
main.zig:6:48: error: function 'main.depth' uses its own inferred error set here
const inner = depth(text[1..]) catch |err| switch (err) {
^~~~~~

Zig can’t finish working out depth’s error set while depth itself asks what’s in it. Give it a name, and the problem is gone:

const std = @import("std");
const DepthError = error{NotABracket};
fn depth(text: []const u8) DepthError!u32 {
if (text.len == 0) return 0;
if (text[0] != '(') return error.NotABracket;
const inner = depth(text[1..]) catch |err| switch (err) {
error.NotABracket => return err,
};
return inner + 1;
}
pub fn main() void {
std.debug.print("{!d}\n", .{depth("(((")});
std.debug.print("{!d}\n", .{depth("((x")});
}

Output:

3
error.NotABracket

(A recursive function that just passes errors on with try does compile with !T. It’s switching on its own errors that needs the explicit set.)

Not sure which errors a function can return? The reference suggests a neat trick: start with the empty set error{} and let the compiler tell you what’s missing:

const std = @import("std");
fn parseLevel(text: []const u8) error{}!u8 {
if (text.len == 0) return error.Empty;
const n = try std.fmt.parseInt(u8, text, 10);
if (n > 10) return error.TooHigh;
return n;
}
pub fn main() void {
std.debug.print("{!d}\n", .{parseLevel("7")});
}
main.zig:4:37: error: expected type 'error{}!u8', found 'error{Empty}'
if (text.len == 0) return error.Empty;
^~~~~
main.zig:4:37: note: 'error.Empty' not a member of destination error set

Add Empty to the set, build again, and the next error names the next missing piece. A few rounds later you have error{ Empty, InvalidCharacter, Overflow, TooHigh }, and you know for sure it’s complete.

Errors with details: the diagnostics pattern

Section titled “Errors with details: the diagnostics pattern”

Here’s the limit you’ll hit soonest. An error is only a name. error.BadNumber can’t say which line or what text was wrong. That’s on purpose (errors stay tiny and never need memory), but users need details.

The usual Zig answer is a diagnostics struct: the caller makes an empty struct and passes a pointer to it. When the function fails, it fills in the details and returns an error. The standard library does this too: std.json and std.zon have a Diagnostics type for exactly this reason.

const std = @import("std");
const ParseError = error{ MissingEquals, EmptyKey, BadNumber };
const Diagnostics = struct {
line: usize = 0,
text: []const u8 = "",
};
const Setting = struct {
key: []const u8,
value: u32,
};
fn parseLine(line: []const u8) ParseError!Setting {
const eq = std.mem.findScalar(u8, line, '=') orelse return error.MissingEquals;
const key = std.mem.trim(u8, line[0..eq], " ");
if (key.len == 0) return error.EmptyKey;
const value_text = std.mem.trim(u8, line[eq + 1 ..], " ");
const value = std.fmt.parseInt(u32, value_text, 10) catch return error.BadNumber;
return .{ .key = key, .value = value };
}
fn parseConfig(text: []const u8, diag: *Diagnostics) ParseError!u32 {
var count: u32 = 0;
var lines = std.mem.splitScalar(u8, text, '\n');
var line_no: usize = 0;
while (lines.next()) |line| {
line_no += 1;
if (line.len == 0) continue;
const setting = parseLine(line) catch |err| {
diag.* = .{ .line = line_no, .text = line };
return err;
};
std.debug.print(" {s} = {d}\n", .{ setting.key, setting.value });
count += 1;
}
return count;
}
pub fn main() void {
const config =
\\width = 80
\\height = 24
\\colors = many
\\depth = 3
;
var diag: Diagnostics = .{};
if (parseConfig(config, &diag)) |count| {
std.debug.print("read {d} settings\n", .{count});
} else |err| {
std.debug.print("config error on line {d}: {t}\n", .{ diag.line, err });
std.debug.print(" the line was: '{s}'\n", .{diag.text});
}
}

Output:

width = 80
height = 24
config error on line 3: BadNumber
the line was: 'colors = many'

How it fits together:

  1. main makes var diag: Diagnostics = .{}; and passes &diag, a pointer, so parseConfig can write into it.
  2. parseLine only knows about one line, so it just returns an error.
  3. parseConfig knows the line number. When parseLine fails, it fills in diag and passes the same error on with return err.
  4. main uses the error to decide what happened and diag to tell the user where.

The error still does what errors do best: try, catch and switch all work as before, and the error return trace still shows the path. The struct just carries the extra facts. The \\ lines are a multiline string literal (see Zig Strings).

When it’s not really an error: return a tagged union

Section titled “When it’s not really an error: return a tagged union”

Sometimes “failing” is a normal answer that the caller always looks at, and it comes with data. Checking a username is a good example: “too short, you gave 2 letters” isn’t a crash, it’s a result to show the user. For that, a tagged union is often cleaner than an error:

const std = @import("std");
const NameCheck = union(enum) {
ok,
too_short: usize,
bad_char: u8,
};
fn checkName(name: []const u8) NameCheck {
if (name.len < 3) return .{ .too_short = name.len };
for (name) |c| {
if (!std.ascii.isAlphanumeric(c)) return .{ .bad_char = c };
}
return .ok;
}
pub fn main() void {
const names = [_][]const u8{ "zigfan", "al", "bob!" };
for (names) |name| {
switch (checkName(name)) {
.ok => std.debug.print("{s}: looks good\n", .{name}),
.too_short => |len| std.debug.print("{s}: only {d} letters, need 3\n", .{ name, len }),
.bad_char => |c| std.debug.print("{s}: '{c}' isn't allowed\n", .{ name, c }),
}
}
}

Output:

zigfan: looks good
al: only 2 letters, need 3
bob!: '!' isn't allowed

Each case carries exactly the data it needs, and the switch makes the caller handle all of them. The trade-off: you lose try, so it doesn’t pass up through other functions by itself. A simple guide: if callers mostly pass it on, use an error (plus diagnostics if needed). If callers always look at it right away, a tagged union is fine.

Make const NetError = error{ Timeout, Refused }; and const AuthError = error{ BadPassword, Locked };, and merge them into LoginError. Write fn login(code: u8) LoginError!void that returns a different error for codes 1 to 4 and succeeds for 0. Print what happens for codes 0 to 4.

Hint: for a !void result, if (login(code)) { ... } else |err| { ... } has no value capture, only the error one.

Show solution
const std = @import("std");
const NetError = error{ Timeout, Refused };
const AuthError = error{ BadPassword, Locked };
const LoginError = NetError || AuthError;
fn login(code: u8) LoginError!void {
switch (code) {
1 => return error.Timeout,
2 => return error.Refused,
3 => return error.BadPassword,
4 => return error.Locked,
else => {},
}
}
pub fn main() void {
for (0..5) |i| {
const code: u8 = @intCast(i);
if (login(code)) {
std.debug.print("{d}: logged in\n", .{code});
} else |err| {
std.debug.print("{d}: {t}\n", .{ code, err });
}
}
}

Output:

0: logged in
1: Timeout
2: Refused
3: BadPassword
4: Locked

LoginError holds all four errors. for (0..5) gives usize values, so @intCast turns each into the u8 that login takes; it always fits here.

Write fn sumWords(text: []const u8, diag: *Diag) !u32 that adds up space-separated numbers like "4 8 15". If a word isn’t a number, store it in diag.word and return error.NotANumber. Test it with "4 8 15" and "4 eight 15".

Hint: use std.mem.tokenizeScalar(u8, text, ' '), and const Diag = struct { word: []const u8 = "" };.

Show solution
const std = @import("std");
const Diag = struct { word: []const u8 = "" };
fn sumWords(text: []const u8, diag: *Diag) !u32 {
var total: u32 = 0;
var words = std.mem.tokenizeScalar(u8, text, ' ');
while (words.next()) |word| {
const n = std.fmt.parseInt(u32, word, 10) catch {
diag.word = word;
return error.NotANumber;
};
total += n;
}
return total;
}
pub fn main() void {
const inputs = [_][]const u8{ "4 8 15", "4 eight 15" };
for (inputs) |text| {
var diag: Diag = .{};
if (sumWords(text, &diag)) |total| {
std.debug.print("'{s}' adds up to {d}\n", .{ text, total });
} else |err| {
std.debug.print("'{s}': {t} ('{s}')\n", .{ text, err, diag.word });
}
}
}

Output:

'4 8 15' adds up to 27
'4 eight 15': NotANumber ('eight')

The error says what kind of problem it was, and diag.word says which word caused it. diag.word is a slice of the input text, so filling it in needs no memory and can’t fail.

  • Give each area of your program its own small error set, with names that say what went wrong.
  • A || B merges two error sets. A smaller set coerces into a bigger one, never the other way.
  • Merge the standard library’s sets too, like std.mem.Allocator.Error for OutOfMemory.
  • !T is great for private helpers; a named set documents public functions and is needed for recursion that switches on its own errors.
  • Start from error{} and let the compiler list what’s missing.
  • Errors carry no data. For details, pass a diagnostics struct pointer and fill it in before returning the error.
  • If callers always inspect the result right away, a tagged union can be simpler than an error.

Next up: Zig Comptime, code that runs while your program compiles.

Quick check

1. What does const LoadError = ReadError || ParseError; create?
2. A function returns LoadError!u16. Inside, can you write try readFile(name) where readFile returns ReadError![]const u8?
3. How do you tell the caller which line of a file had a bad number?
4. A recursive function with !u32 switches on its own errors and fails to compile. What is the fix?