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

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