In the parser I just created, I often need to be sure that a certain token is in a certain place, for example let must be followed by an identifier token. I use this method for this kind of check:
It does the job fine, but I would really like to display a useful error message to the user. For example, for this source code if @, I would like to output Expected token '(', given '@'. Tell me if I am wrong, error sets doesn’t bring any context besides names.
I can read here that std.log.err is recommended by the participants of the conversation. But I am not a big fan of having hidden global dependencies in the code, maybe I should use a custom logger?
I can see in the std.testing that std.debug is used via a print function. But maybe std.err makes more sense for my use case.
Wdyt? I am really used to work with exceptions in other languages, so I am not sure how to do the right thing with zig.
The usual pattern I use is to pass additional error information out of band. Either through an additional parameter that the caller may provide (e.g errinfo: ?*MyErrorInfo), or via a fn getLastErrorInfo() MyErrorInfo function of some sort that retrieves additional info from some library internal place (usually threadlocal).
I am also interested in a pattern to show useful information.
The main feeling I have with the error handling in Zig is that it is extremely compact and clear. The perfect mechanism in my opinion. And I hope nothing changes here in the anguage.
But indeed when going through a complicated decompression algorithm we would like to have detailed information, where something went wrong.
I do not like the idea of passing some optional parameter everywhere, to optionally store something.
How can this be used with zig’s regular error handling try/catch? I doesn’t seem very nice if you have to implement you own custom mechanisms but I’d like to see how it’s done
Maybe you could create, a global ErrorReporting struct, which holds an allocator, and some functions. So when you call expect, you can catch the error, and pass it to ErrorReporting with some more context like you could have a type TokenSourceLocation that ressemble a bit like what you have with the @src() builtin, but custom made for your usecase. Then whatever Errors you get, from a function that has to do with the code you are parsing not with system errors, you can report them more elegantly.
Ok looks clear.
So at a higher level, when a parseerror occurs, we have to know we have to inspect this global? pub var parse_error_message: []const u8 = "";
Yes, you have to just know (or document) that this is the place to get more detail on this particular error. If you want it to be more explicit you should probably require an errorInfo parameter of some sort.