Error payloads in Zig
25 points by winter
25 points by winter
Big fan of sharing this as a gist. I know its polarizing, but I'm very strongly on the side that we should be copying and pasting more code and the downsides about it are mostly fear mongering (imo, many many more issues come up by updating/changing code than by considering it done).
The line is grey of course but stuff like this where it all fits in a single file and isn't security sensitive (no networking, crypto, file access, etc.) should just be copied and pasted and the gist encourages that.
My only recommendation would be to add some tests to the file. :)
We should be using more snippets too. Snippets are superpowered copy and paste, and LSP only gets us half of the way there.
Thanks for taking a look! It means a lot!!
I have added some sample code tests to the gist. There's a toy allocator which uses its diag to recommend a specific smaller alloc size on OOM.
There is also a "process list of things" style of struct. This one gives 2 different error payloads. Both payloads include failed index, so callers can log and resume with the remainder if they want (even if just to collect all the failures). One of the payloads includes the toy allocator context, while the other one copies a DB error into an inline struct buffer and has a slice method.
One thing that is helpful to anyone downstream of that is to also slap a big provenance comment at the top of the file (well, the snippet should probably have one). Can be a license on top of it, but just like "here's this thing from this gist gotten at this point in time". That + the magic of version control and honestly we're in a good spot
That is indeed more or less what you commonly do when you need something more than just error codes.
As an example: https://github.com/kristoff-it/ziggy/blob/852053b09a5f8f5b79ca880f86ea77fc7da3dd6c/src/Ast.zig#L18-L50
The part about mapping every error kind to different error code in Zig is debatable. It might be useful in some cases maybe (I don't have the confidence to fully exclude it), but at the very least in my experience I never ever needed that.