Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Created July 17, 2022 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnakamur/73dbfb38f3ce1a1591f3c594906ff01c to your computer and use it in GitHub Desktop.
Save hnakamur/73dbfb38f3ce1a1591f3c594906ff01c to your computer and use it in GitHub Desktop.
An example of returning a dynamic error message in Zig
const std = @import("std");
const Context = struct {
canceled: bool = false,
err: [4096]u8 = undefined,
pub fn formatErr(self: *Context, comptime fmt: []const u8, args: anytype) error{NoSpaceLeft}!void {
var fbs = std.io.fixedBufferStream(self.err[0..]);
var writer = fbs.writer();
try std.fmt.format(writer, fmt, args);
}
};
const ContextError = error{InternalError, NoSpaceLeft};
fn do_something(ctx: *Context, input: i32) ContextError!void {
if (input < 10) {
ctx.canceled = true;
try ctx.formatErr("less than 10: was {}", .{input});
return error.InternalError;
}
}
pub fn main() !void {
var ctx = Context{};
do_something(&ctx, 9) catch |err| {
std.log.err("{s}", .{ctx.err});
return err;
};
}
$ zig run dynamic_error_msg.zig
error: less than 10: was 9
error: InternalError
/home/hnakamur/ghq/github.com/hnakamur/learn-zig/dynamic_error_msg.zig:20:9: 0x22a49e in do_something (dynamic_error_msg)
return error.InternalError;
^
/home/hnakamur/ghq/github.com/hnakamur/learn-zig/dynamic_error_msg.zig:28:9: 0x228224 in main (dynamic_error_msg)
return err;
^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment