Zig Error Return Traces
With try everywhere, an error can travel through many functions before something handles it, or before it falls out of main. By then, a bare error: FileNotFound doesn’t tell you much. Which file? Which call? Zig answers that with an error return trace: a list of every place the error was returned on its way up. It’s one of Zig’s nicest debugging features, and it costs you nothing to use in a normal debug build. This lesson shows how to read one, how to print one yourself, and how build modes change it.
Your first error return trace
Section titled “Your first error return trace”Here an error starts deep down and is passed up twice with try:
const std = @import("std");
fn readConfig(path: []const u8) ![]const u8 { if (path.len == 0) return error.FileNotFound; return "port=8080";}
fn loadSettings() ![]const u8 { const text = try readConfig(""); return text;}
pub fn main() !void { const settings = try loadSettings(); std.debug.print("settings: {s}\n", .{settings});}You’ll see something like:
error: FileNotFoundmain.zig:4:24: 0x11e4163 in readConfig (main.zig) if (path.len == 0) return error.FileNotFound; ^main.zig:9:18: 0x11e422f in loadSettings (main.zig) const text = try readConfig(""); ^main.zig:14:22: 0x11e4332 in main (main.zig) const settings = try loadSettings(); ^The first line is the error that came out of main. Below it, each entry has the same shape: file:line:column, an address you can ignore, the function name, then the line of code with a ^ under the exact spot. On your machine the file name is the full path, and the addresses differ.
Read it top to bottom, in the order things happened:
readConfig, line 4:return error.FileNotFoundis where the error was born.loadSettings, line 9: atrypassed it up.main, line 14: anothertrypassed it out ofmain.
So the bug is the empty path given to readConfig on line 9. You found it without adding a single print line.
Why it’s better than a stack trace
Section titled “Why it’s better than a stack trace”An error return trace remembers things a stack trace can’t: errors that were already handled and turned into something else. Here, loadSettings falls back to a backup file when the real one is missing, but the backup can’t be opened either:
const std = @import("std");
fn openFile(name: []const u8) !void { if (std.mem.eql(u8, name, "settings.txt")) return error.FileNotFound; if (std.mem.eql(u8, name, "backup.txt")) return error.AccessDenied;}
fn loadSettings() !void { openFile("settings.txt") catch |err| switch (err) { error.FileNotFound => try openFile("backup.txt"), else => return err, };}
pub fn main() !void { try loadSettings();}You’ll see something like:
error: AccessDeniedmain.zig:4:48: 0x11e4174 in openFile (main.zig) if (std.mem.eql(u8, name, "settings.txt")) return error.FileNotFound; ^main.zig:5:46: 0x11e41ac in openFile (main.zig) if (std.mem.eql(u8, name, "backup.txt")) return error.AccessDenied; ^main.zig:10:31: 0x11e42a5 in loadSettings (main.zig) error.FileNotFound => try openFile("backup.txt"), ^main.zig:16:5: 0x11e43a7 in main (main.zig) try loadSettings(); ^The final error is AccessDenied, but the trace starts one step earlier: settings.txt wasn’t found (line 4), then the backup was refused (line 5), and that’s the error that reached main. A stack trace would only show you where the program was at the very end. This trace tells the whole story: “the real file is missing, and that’s why we touched the backup at all”.
If the backup had opened fine, the FileNotFound would have been handled for good, and it wouldn’t show up in any later trace. Zig only keeps the errors that are part of the path to the error you’re looking at.
Printing the trace yourself
Section titled “Printing the trace yourself”When you handle an error instead of letting it out of main, you can still look at its trace. @errorReturnTrace() gives you the current trace, and std.debug.dumpErrorReturnTrace prints it to stderr:
const std = @import("std");
fn readConfig() !void { return error.FileNotFound;}
fn loadSettings() !void { try readConfig();}
pub fn main() void { loadSettings() catch |err| { std.debug.print("could not load settings: {t}\n", .{err}); if (@errorReturnTrace()) |trace| std.debug.dumpErrorReturnTrace(trace); std.debug.print("using defaults instead\n", .{}); };}You’ll see something like:
could not load settings: FileNotFoundmain.zig:4:5: 0x11e4dbc in readConfig (main.zig) return error.FileNotFound; ^main.zig:8:5: 0x11e4e17 in loadSettings (main.zig) try readConfig(); ^using defaults instead@errorReturnTrace() returns an optional pointer, ?*std.lang.StackTrace. It’s null when error tracing is turned off (see the next section), which is why we unwrap it with if (...) |trace|, the same as any optional. Written like this, the code works in every build mode: with tracing, you get the details; without it, you get just the message.
This is handy in a server or a long-running tool, where you don’t want one failed request to stop the whole program, but you do want to see where it went wrong. The language reference on @errorReturnTrace has the short official description.
Build modes: on in debug, off in the others
Section titled “Build modes: on in debug, off in the others”Error return tracing is turned on by default only in debug builds, which is what zig run and zig build give you unless you ask for something else. In safe, fast and small it’s off, and the first example only prints this:
zig run -O safe main.zigYou’ll see:
error: FileNotFoundThe error name is still there, and the exit code is still 1, but the trace is gone. You can switch tracing back on with -ferror-tracing (and off with -fno-error-tracing):
zig run -O safe -ferror-tracing main.zigYou’ll see something like:
error: FileNotFoundmain.zig:4:24: 0x101bafb in readConfig (main) if (path.len == 0) return error.FileNotFound; ^main.zig:9:18: 0x101bb03 in loadSettings (main) const text = try readConfig(""); ^main.zig:14:22: 0x101bb0b in main (main) const settings = try loadSettings(); ^In a project with a build.zig, set error_tracing on the module instead. In the file zig init makes, it goes next to .optimize:
.root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, .error_tracing = true,}),Then zig build run -Doptimize=safe prints the full trace too. Zig Build Modes and Zig Build System cover the rest of those settings.
One more thing turns traces off: stripping debug information (-fstrip, or .strip = true in build.zig). Without it, Zig can’t turn addresses back into file names and lines, so you get just error: FileNotFound again.
Traces in panics too
Section titled “Traces in panics too”You’ve already seen a trace hiding inside a panic. When catch unreachable meets an error (see Zig Try & Catch), the panic message includes an error return context: the error’s trace, followed by the normal stack trace:
thread 1029 panic: attempt to unwrap error: InvalidCharactererror return context:std/fmt.zig:583:24: 0x10f4e5a in charToDigit (std.zig) if (value >= base) return error.InvalidCharacter; ^...
stack trace:main.zig:7:53: 0x11e3e85 in main (main.zig) total += std.fmt.parseInt(u32, s, 10) catch unreachable; ^Read it the same way: the “error return context” part shows where the error was born (here, deep inside the standard library’s number parser), and the “stack trace” part shows where your code gave up. Seeing std/... files at the top is normal: errors often start in the standard library, and the interesting line is usually the first one in your files.
Practice
Section titled “Practice”1. Find the bug from the trace
Section titled “1. Find the bug from the trace”Run this in a debug build. Using only the trace, find which call to price caused the error, then fix the data so the program prints a total.
const std = @import("std");
fn price(item: []const u8) !u32 { if (std.mem.eql(u8, item, "apple")) return 3; if (std.mem.eql(u8, item, "bread")) return 5; return error.UnknownItem;}
fn total(items: []const []const u8) !u32 { var sum: u32 = 0; for (items) |item| sum += try price(item); return sum;}
pub fn main() !void { const basket = [_][]const u8{ "apple", "bread", "bred" }; std.debug.print("total: {d}\n", .{try total(&basket)});}Hint: the top entry shows where the error was born. The next one shows which line in total passed it on, and the last shows where main called it.
Show solution
You’ll see something like:
error: UnknownItemmain.zig:6:5: 0x11e41bd in price (main.zig) return error.UnknownItem; ^main.zig:11:31: 0x11e42ce in total (main.zig) for (items) |item| sum += try price(item); ^main.zig:17:39: 0x11e4480 in main (main.zig) std.debug.print("total: {d}\n", .{try total(&basket)}); ^The error was born in price because an item wasn’t recognized, and the only item that isn’t "apple" or "bread" is the typo "bred". Change it to "bread" and the program prints total: 13. The trace can’t tell you which item it was (errors carry no data), but it narrows the search to one line. Zig Custom Error Sets shows how to report the bad item itself.
2. Log and carry on
Section titled “2. Log and carry on”Change the solution’s main so it handles the error itself: print could not price the basket: plus the error name, then the trace with @errorReturnTrace(), and finish with done. Keep "bred" in the basket so the error still happens. main should return void.
Hint: total(&basket) catch |err| { ... return; } and if (@errorReturnTrace()) |t| std.debug.dumpErrorReturnTrace(t);.
Show solution
const std = @import("std");
fn price(item: []const u8) !u32 { if (std.mem.eql(u8, item, "apple")) return 3; if (std.mem.eql(u8, item, "bread")) return 5; return error.UnknownItem;}
fn total(items: []const []const u8) !u32 { var sum: u32 = 0; for (items) |item| sum += try price(item); return sum;}
pub fn main() void { const basket = [_][]const u8{ "apple", "bread", "bred" }; const sum = total(&basket) catch |err| { std.debug.print("could not price the basket: {t}\n", .{err}); if (@errorReturnTrace()) |t| std.debug.dumpErrorReturnTrace(t); std.debug.print("done\n", .{}); return; }; std.debug.print("total: {d}\n", .{sum});}You’ll see something like:
could not price the basket: UnknownItemmain.zig:6:5: 0x11e4e3d in price (main.zig) return error.UnknownItem; ^main.zig:11:31: 0x11e4f4e in total (main.zig) for (items) |item| sum += try price(item); ^doneThe program now ends normally (exit code 0), but you still see where the error came from. Run it with -O safe and the trace lines disappear, because @errorReturnTrace() returns null there.
- An error return trace lists every
returnandtryan error passed through, oldest first. - The top entry is where the error was born; that’s usually the first place to look.
- It also keeps earlier errors that were handled but led to the final one.
@errorReturnTrace()gives the trace as an optional; print it withstd.debug.dumpErrorReturnTrace.- Tracing is on in
debug, off insafe,fastandsmall. Turn it on with-ferror-tracingor.error_tracing = true. - Stripping debug info (
-fstrip) removes the trace, because file names and lines are gone.
Next up: Zig Illegal Behavior & Panics, the bugs Zig catches at runtime and what build modes do with them.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Error return traces: the official example, the comparison with stack traces, and how the cost works.
- Zig language reference: @errorReturnTrace: getting the trace from your own code.
- Zig language reference: Optimization mode: what each build mode turns on and off.
- Zig Build System guide: where module options like
error_tracingfit in abuild.zig.