I recommend watching the recent SYCL talk How To Avoid Needy Software by @marler8997 if you haven’t already. The core point is that it’s generally a good idea for “this should never happen” type errors to not have complicated error handling and instead crash. However that crash should have good visibility to you (the developer) so that you know that there’s a problem you need to solve. There’s a lot more to why and how in the talk.
I’ll post (yet again) my couple of helper methods I use constantly in code.
pub fn check(v: anytype) @typeInfo(@TypeOf(v)).error_union.payload {
return v catch |err| fatal(err);
}
pub fn fatal(err: anyerror) noreturn {
if (@import("builtin").mode == .Debug) @panic(@errorName(err));
std.debug.print("Fatal error {t}.\n", .{err});
std.process.exit(1);
}
Usage looks like:
const xxx = check(gpa.alloc(...));
The implementation of fatal should change dramatically based on the application. I liked the suggestion in the above talk for having a pop-up box with a contact e-mail for reporting the issue. I originally took a @src argument, but ended up pulling it out because it was redundant with stack traces.
A few random assorted thoughts:
For my game, I’ve gone all in on “just crash” on all of my memory allocations. It’s a fairly lightweight game, and (as suggested above) it typically actually takes work to get the OS to actually give you an out of memory error. I suspect too many badly programmed applications have such bad behavior from OOM that they put a lot of effort into never giving that error.
If you’re able to contain the memory allocations to initial loading, or level loading, that’s ideal. Initial loading would still probably just crash, but level loading could, eg, push you back to the main menu.
If you’re writing something like photoshop, ideally each operation can be backtracked to before the resources are required. So you don’t crash and lose all of your work. You could also put some code to try save all documents in your fatal function.
For web servers, yeah you want to just return errors to the individual request. If you’re trying to do something heavy duty, I recommend reading up on load shedding, and probably the banker’s algorithm. Better to fail fast and early and keep the request queue length low. Also, lifo > fifo.