Function prototypes that return an error

Hello,
I need help with designing my application. I have a struct like this:

pub const Route = struct {
    path: []const u8,
    handler: *const fn (
        allocator: Allocator,
        req: HttpRequestInfo,
    ) []const u8,
};

What the zig compiler doesn’t allow me is to have the handler field return ![]const u8. This makes error handling very annoying, because I can’t use try inside of the handler to catch the error later on by the caller. How can I work around this?

Any help will be appreciated
thanks!

Having the error set be inferred (ie having nothing to the left of the !) makes the function generic which is incompatible with giving a precise type to handler.

One solution is to have the handler return a precise error set, another is to forbid the handler from returning errors at all. Yes that means not being able to use try, but maybe it makes sense for your control flow.

One last option, which might make sense but that makes the type system less effective, is to use type erasure on the returned error set by using anyerror![]const u8 as the return value.

At that point Zig won’t be able to tell you which are the exact errors that could be returned by handler, but it will allow users to give you pointers to functions that return potentially different error sets.

2 Likes