top | item 47039106

(no title)

AndyKelley | 13 days ago

In Zig, error codes are fundamentally a control flow construct, not a reporting mechanism.

The pattern here is to return something like error.Diagnostics for all errors that have been reported via diagnostics.

The only reason you'd have a different error code would be if the control flow should be different. For example error.OutOfMemory makes sense to be separate because it's a retryable error, which means it should be handled by different control flow.

discuss

order

srcreigh|12 days ago

Thanks Andy.

Would you endorse the pattern I described in my article if the calling code could have other uses for the diagnostic info than just logging?

In my project I decided that the CLI main should be the place with a reporting mechanism. All the internal code is agnostic to how errors are handled. Many errors could be retried, even if they are currently not, and in some cases you also need extra diagnostic data in order to retry. For example if 1/4 plugins fails to load, I would need to know which one failed to ask the user interactively where to find it or whether to skip it before retrying. There's a few different errors like this, and layers between the handling code and the error source code, which is how I ended up with the union(enum) diagnostic keyed by error code pattern.

It seems that "error codes aren't a reporting mechanism", practically speaking, means that internal application code should just log its own error and return a generic error code that bubbles up unhandled out of main. You decided that this wasn't ok for allocation failures and encourage retrying those, which I find to be inspiring, but apparently most types of application errors are fine to essentially log and ignore. So that is confusing.

I love Zig, and look up to you a lot, so thanks for all your efforts over the years!

robinei|12 days ago

Do you think it would fundamentally be a mistake to thread data along with error type through the error return path, or is it just that it costs too much say from a calling convention perspective or some other technical reason? Is it related to ownership?