Hi all,
I keep running into a recurring issue with boilerplate and I’m wondering if there is a way to reduce it.
I’m using an atomic Task queue and multi-threading which makes it so that I can’t use “try” in my functions since they all have to have a “void” return type, but that makes error handling very boilerplate heavy.
Here’s an example:
try group.concurrent(io, Server.listen, .{ io, q, "127.0.0.1", 8000 });
elsewhere in the code:
pub fn listen(io: Io, q: *AQ(Task), addr: []const u8, port: u16) void {
const address = std.Io.net.IpAddress.parse(addr, port) catch |e| {
std.log.err("{}", .{e});
return;
};
var server = address.listen(io, .{ .mode = .stream, .reuse_address = true }) catch |e| {
std.log.err("{}", .{e});
return;
};
while (true) {
const conn = server.accept(io) catch |e| {
std.log.err("{}", .{e});
return;
};
// conn.deinit() has to be called by the handler thread
const task = Task{
.handleConn = .{
.call = handleConn,
.args = .{ .io = io, .conn = conn },
},
};
q.enqueue(task) catch |e| {
switch (e) {
error.QueueFull => {
std.debug.print("{} queue full\n", .{std.Thread.getCurrentId()});
try io.sleep(.fromMilliseconds(150), .awake);
continue;
},
error.QueueClosing => {
std.debug.print("tasker {} q is closing\n", .{std.Thread.getCurrentId()});
return;
},
else => {
std.log.err("{}", .{e});
return;
},
}
};
}
}
Is there a way to not have to repeat this pattern over and over?
const x = functionCall() catch |e| {
std.log.err("{}", .{e});
return;
};
I tried using an inline function which would be nice, but the code assumes I’m trying to return a “void” instead of return from the outer function so it doesn’t actually work. Here’s the pattern.
pub inline fn err(caller: []const u8, e: anyerror) void {
std.log.err("{s}: {}", .{ caller, e });
}
Then the previous code becomes:
pub fn listen(io: Io, q: *AQ(Task), addr: []const u8, port: u16) void {
const address = std.Io.net.IpAddress.parse(addr, port) catch |e| err(e);
var server = address.listen(io, .{ .mode = .stream, .reuse_address = true }) catch |e| err(e);
while (true) {
const conn = server.accept(io) catch |e| err(e);
// conn.deinit() has to be called by the handler thread
const task = Task{
.handleConn = .{
.call = handleConn,
.args = .{ .io = io, .conn = conn },
},
};
q.enqueue(task) catch |e| {
switch (e) {
error.QueueFull => {
std.debug.print("{} queue full\n", .{std.Thread.getCurrentId()});
try io.sleep(.fromMilliseconds(150), .awake);
continue;
},
error.QueueClosing => {
std.debug.print("tasker {} q is closing\n", .{std.Thread.getCurrentId()});
return;
},
else => err(e),
}
};
}
}
Is there some other pattern that I’m not aware of or thinking of?
Thanks in advance,
Nik