Sometimes it would be useful to handle errors by switching on groups (sets) at a time. I imagine this might especially come in handy when dealing with third party libraries whose functions categorize errors into sets. This feature would keep code a tiny bit more robust against library upgrades: If that third party library extended one of the error sets it returns, your code would still be handling errors of the same "category" with your existing switch prong.
Let's make believe for a moment:
main.zig
const warn = @import("std").debug.warn; const http = @import("http.zig"); pub fn main() void { const res = http.doRequest() catch |err| switch (err) { http.ClientError => |e| warn("we goofed: {}\n", e), // error set + payload http.ServerError => |_| warn("they goofed\n"), // error set, discard payload error.OutOfMemory => warn("{\n}", err), // error else => unreachable, // else }; warn("response: {}\n", res); }
http.zig
pub fn doRequest() (ClientError || ServerError || error{OutOfMemory})![]const u8 { return ServerError.NotImplemented; } pub const ClientError = error{ BadRequest, Unauthorized, Forbidden, NotFound, }; pub const ServerError = error{ InternalError, NotImplemented, ServiceUnavailable, };
Present-day (0.4.0+dbb5da14
), running zig build-exe main.zig
gives:
error: expected type 'error{BadRequest,Unauthorized,Forbidden,NotFound,InternalError,NotImplemented,ServiceUnavailable,OutOfMemory,}', found 'type'
http.ClientError => |e| warn("we goofed: {}\n", e), // error set + payload
^
Notes
err
just as well as the prong capture e
, since there's nothing to unwrap. (This would not be the case if error sets were unique container values unto themselves rather than global sets -- a separate discussion.)switch (err) { error{Evil, OutOfMemory} => |e| warn("very bad: {}\n", e), else => {}, }
tadeokondrak, pfgithub, alexnask, g-w1, ve-nt and 47 more
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4