Is there a nicer way to check if an error is in an error set?

I thought this would work

test "doesn't work" {
    const err = getErr();
    try testing.expectError(Error1, err);
}

but i got expected type 'anyerror', found 'type'

Heres an example of working code, but as you can see it doesn’t look pretty, and would get annoying if the Error1 were to grow larger or smaller

const std = @import("std");
const testing = std.testing;

const Error1 = error{ Foo, Bar };
const Error2 = error{ Baz, Qux };

const Error = Error1 || Error2;

fn getErr(condition: bool) Error!void {
    if (condition) {
        return Error2.Qux;
    }
    return Error1.Foo;
}

test "does work" {
    getErr(false) catch |errors| switch (errors) {
        Error1.Bar, Error1.Foo => return,
        else => return error.IncorrectErrors,
    };

    return error.IsNotError;
}

Is there a better way to check if an error received is within a set of errors? or am i going about this the wrong way and should use errors differently, if so please point me to the right direction.

1 Like

expectError takes a specific error value as it’s first argument, e.g Error1.Foo, not a whole error set.

Here’s a function which tests that a result is an error within the given error set, it takes a bit of type reflection:

fn expectErrorSet(ErrorSet: type, result: anytype) !void {
    if (result) |_| {
        return error.NotAnError;
    } else |err| {
        if (@typeInfo(ErrorSet).error_set) |error_set| for (error_set) |err_info| {
            if (std.mem.eql(u8, @errorName(err), err_info.name)) {
                return;
            }
        };

        return error.NotInErrorSet;
    }
}

test "does work" {
    try expectErrorSet(Error1, getErr(false));

    try std.testing.expectError(
        error.NotInErrorSet,
        expectErrorSet(Error1, getErr(true)),
    );
}
4 Likes

Thank you, that’s exactly whats I’m looking for.

EDIT: Nevermind; realized you want something that works on a runtime error.

comptime error set helper function stuff There are some nice helper functions for this (and other error set stuff) in this PR:

Unfortunately it was rejected, but you could copy what you want into your project.