# Displaying error messages

**URL:** <https://ziggit.dev/t/displaying-error-messages/6952>\
**Category:** Help\
**Tags:** error-handling\
**Created:** [November 21, 2024, 8:39pm UTC](https://ziggit.dev/t/displaying-error-messages/6952 "2024-11-21T20:39:41Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![jean-michelet](https://ziggit.dev/user_avatar/ziggit.dev/jean-michelet/32/3739_2.png) [@jean-michelet](https://ziggit.dev/u/jean-michelet)\
**Post date:** [November 21, 2024, 8:39pm UTC](https://ziggit.dev/t/displaying-error-messages/6952/1 "2024-11-21T20:39:41Z")

</div>

Hi!

In [the parser I just created](https://github.com/jean-michelet/Eduscript-VM/blob/main/src/parser/parser.zig), I often need to be sure that a certain token is in a certain place, for example `let` must be followed by an `identifier` token. I use this method for this kind of check:

```zig
fn expect(self: *@This(), token_type: Token.Type) Errors!void {
    if (self.peek().token_type != token_type) {
        return Errors.UnexpectedToken;
    }
}

```

It does the job fine, but I would really like to display a useful error message to the user. For example, for this source code `if @`, I would like to output `Expected token '(', given '@'`. Tell me if I am wrong, `error` sets doesn’t bring any context besides names.

I can read [here](https://ziggit.dev/t/error-handling-with-custom-messages/2645) that `std.log.err` is recommended by the participants of the conversation. But I am not a big fan of having hidden global dependencies in the code, maybe I should use a custom logger?

I can see in the [std.testing](https://github.com/ziglang/zig/blob/f845fa04a0dce3104efe129c73a6ad792b1712b6/lib/std/testing.zig#L31) that `std.debug` is used via a `print` function. But maybe `std.err` makes more sense for my use case.

Wdyt? I am really used to work with exceptions in other languages, so I am not sure how to do the right thing with zig.

---

<div class="post-metadata">

**Author:** ![neurocyte](https://ziggit.dev/user_avatar/ziggit.dev/neurocyte/32/3804_2.png) [@neurocyte](https://ziggit.dev/u/neurocyte)\
**Post date:** [November 21, 2024, 9:01pm UTC](https://ziggit.dev/t/displaying-error-messages/6952/2 "2024-11-21T21:01:30Z")

</div>

The usual pattern I use is to pass additional error information out of band. Either through an additional parameter that the caller may provide (e.g `errinfo: ?*MyErrorInfo`), or via a `fn getLastErrorInfo() MyErrorInfo` function of some sort that retrieves additional info from some library internal place (usually `threadlocal`).

---

<div class="post-metadata">

**Author:** ![jean-michelet](https://ziggit.dev/user_avatar/ziggit.dev/jean-michelet/32/3739_2.png) [@jean-michelet](https://ziggit.dev/u/jean-michelet)\
**Post date:** [November 21, 2024, 9:14pm UTC](https://ziggit.dev/t/displaying-error-messages/6952/3 "2024-11-21T21:14:38Z")

</div>

Thanks for you answer!

Do you have any project to share that implement this pattern?

---

<div class="post-metadata">

**Author:** ![ericlang](https://ziggit.dev/user_avatar/ziggit.dev/ericlang/32/8515_2.png) [@ericlang](https://ziggit.dev/u/ericlang)\
**Post date:** [November 21, 2024, 9:30pm UTC](https://ziggit.dev/t/displaying-error-messages/6952/4 "2024-11-21T21:30:30Z")

</div>

I am also interested in a pattern to show useful information.  
The main feeling I have with the error handling in Zig is that it is _extremely_ compact and clear. The perfect mechanism in my opinion. And I hope nothing changes here in the anguage.

But indeed when going through a complicated decompression algorithm we would like to have detailed information, where something went wrong.

I do not like the idea of passing some optional parameter everywhere, to optionally store something.

What would be a good generic solution?

---

<div class="post-metadata">

**Author:** ![neurocyte](https://ziggit.dev/user_avatar/ziggit.dev/neurocyte/32/3804_2.png) [@neurocyte](https://ziggit.dev/u/neurocyte)\
**Post date:** [November 21, 2024, 10:19pm UTC](https://ziggit.dev/t/displaying-error-messages/6952/5 "2024-11-21T22:19:19Z")

</div>

Here is a fairly concise example: [flow/src/keybind/dynamic/parse\_flow.zig at master · neurocyte/flow · GitHub](https://github.com/neurocyte/flow/blob/master/src%2Fkeybind%2Fdynamic%2Fparse_flow.zig#L16)

---

<div class="post-metadata">

**Author:** ![ktz\_alias](https://ziggit.dev/user_avatar/ziggit.dev/ktz_alias/32/1202_2.png) [@ktz\_alias](https://ziggit.dev/u/ktz_alias)\
**Post date:** [November 22, 2024, 3:47am UTC](https://ziggit.dev/t/displaying-error-messages/6952/6 "2024-11-22T03:47:30Z")

</div>

As the other approach, I often use `Result` pattern with the tagged union but need to take care of the heap allocation.

```zig
const std = @import("std");

fn Result(comptime SuccessResult: type, comptime ErrorResult: type) type {
    return union(enum) {
        ok: SuccessResult,
        err: ErrorResult,
    };
}

const MyResult = Result(u8, []const u8);

pub fn main() !void {
    const r1: MyResult = .{.ok = 42};
    const r2: MyResult = .{.err = "Oops!"};

    std.debug.print("ok: {}, err: {}\n", .{r1, r2});
}

```

---

<div class="post-metadata">

**Author:** ![jean-michelet](https://ziggit.dev/user_avatar/ziggit.dev/jean-michelet/32/3739_2.png) [@jean-michelet](https://ziggit.dev/u/jean-michelet)\
**Post date:** [November 22, 2024, 6:20am UTC](https://ziggit.dev/t/displaying-error-messages/6952/7 "2024-11-22T06:20:38Z")

</div>

Thanks! This is an interesting approach.

---

<div class="post-metadata">

**Author:** ![jean-michelet](https://ziggit.dev/user_avatar/ziggit.dev/jean-michelet/32/3739_2.png) [@jean-michelet](https://ziggit.dev/u/jean-michelet)\
**Post date:** [November 22, 2024, 6:21am UTC](https://ziggit.dev/t/displaying-error-messages/6952/8 "2024-11-22T06:21:52Z")

</div>

Saw this in an article yep.

---

<div class="post-metadata">

**Author:** ![ajoino](https://ziggit.dev/user_avatar/ziggit.dev/ajoino/32/3120_2.png) [@ajoino](https://ziggit.dev/u/ajoino)\
**Post date:** [November 22, 2024, 8:42am UTC](https://ziggit.dev/t/displaying-error-messages/6952/9 "2024-11-22T08:42:07Z")

</div>

How can this be used with zig’s regular error handling `try`/`catch`? I doesn’t seem very nice if you have to implement you own custom mechanisms but I’d like to see how it’s done

---

<div class="post-metadata">

**Author:** ![pierrelgol](https://ziggit.dev/user_avatar/ziggit.dev/pierrelgol/32/10233_2.png) [@pierrelgol](https://ziggit.dev/u/pierrelgol)\
**Post date:** [November 22, 2024, 9:01am UTC](https://ziggit.dev/t/displaying-error-messages/6952/10 "2024-11-22T09:01:24Z")

</div>

Maybe you could create, a global `ErrorReporting` struct, which holds an allocator, and some functions. So when you call expect, you can catch the error, and pass it to `ErrorReporting` with some more context like you could have a type `TokenSourceLocation` that ressemble a bit like what you have with the `@src()` builtin, but custom made for your usecase. Then whatever Errors you get, from a function that has to do with the code you are parsing not with system errors, you can report them more elegantly.

---

<div class="post-metadata">

**Author:** ![ktz\_alias](https://ziggit.dev/user_avatar/ziggit.dev/ktz_alias/32/1202_2.png) [@ktz\_alias](https://ziggit.dev/u/ktz_alias)\
**Post date:** [November 22, 2024, 9:15am UTC](https://ziggit.dev/t/displaying-error-messages/6952/11 "2024-11-22T09:15:12Z")

</div>

For instance:

```zig
fn foo(allocator: std.mem.Allocator) !Result(u8, []const u8) {
    return result: {
        if (validateBar()) |x| {
            break:result .{.ok = x};
        }
        else |err| {
            break:result .{.err = try std.fmt.allocPrint("Error occured: {}", .{err})};
        }
    };
}

pub fn main() !void {
    const gpa = ...;
    var arena = std.heap.ArenaAllocator.init(gpa);
    arena.deinit();

    switch (try foo(arena.allocator())) {
        .ok => |value| { ... },
        .err => |msg| { ...},
    };
}

```

I used this approach to handle errors for CLI arguments.

> <https://github.com/ritalin/zig-omelet/blob/main/runner/src/settings/Setting.zig#L41>

---

<div class="post-metadata">

**Author:** ![ajoino](https://ziggit.dev/user_avatar/ziggit.dev/ajoino/32/3120_2.png) [@ajoino](https://ziggit.dev/u/ajoino)\
**Post date:** [November 22, 2024, 9:50am UTC](https://ziggit.dev/t/displaying-error-messages/6952/12 "2024-11-22T09:50:42Z")

</div>

Ok, I see it circumvents the regular error mechanisms. Thanks!

---

<div class="post-metadata">

**Author:** ![ericlang](https://ziggit.dev/user_avatar/ziggit.dev/ericlang/32/8515_2.png) [@ericlang](https://ziggit.dev/u/ericlang)\
**Post date:** [November 22, 2024, 10:08pm UTC](https://ziggit.dev/t/displaying-error-messages/6952/13 "2024-11-22T22:08:27Z")

</div>

Ok looks clear.  
So at a higher level, when a parseerror occurs, we have to know we have to inspect this global?  
`pub var parse_error_message: []const u8 = "";`

---

<div class="post-metadata">

**Author:** ![neurocyte](https://ziggit.dev/user_avatar/ziggit.dev/neurocyte/32/3804_2.png) [@neurocyte](https://ziggit.dev/u/neurocyte)\
**Post date:** [November 26, 2024, 5:17am UTC](https://ziggit.dev/t/displaying-error-messages/6952/14 "2024-11-26T05:17:40Z")

</div>

Yes, you have to just know (or document) that this is the place to get more detail on this particular error. If you want it to be more explicit you should probably require an errorInfo parameter of some sort.
