|
|
|
|
|
by malcolmstill
1203 days ago
|
|
I see you what you mean. Yeah, I suppose if you are writing a library you might want to be more deliberate in the error set. Maybe explicitly writing out the error set is what you want in that situation. Rewriting the example: fn someFunction(a: usize) MyError!usize {
if (a < 10) return error.LessThanTen;
const b = try anotherFunction(a);
return 2 * b;
}
fn anotherFunction(x: usize) MyError!usize {
if (x < 20) return error.LessThanTwenty;
return x * 3;
}
const MyError = error {
LessThanTen,
LessThanTwenty
}
> That feels very limiting, I often use error types to e.g., attach data about the error. Is there a more general mechanism for sum types for when this shorthand doesn't apply?I agree it's limiting. It obviously is going to depend on your application, but I have largely done without annotating errors with extra information (that maybe speaks more to the seriousness of my zig projects than to that approach to error handling as being sufficient!). One pattern I have used (in e.g. a parser) is additionally passing in a pointer to a sum type: fn parse(allocator: *mem.Allocator, tokens: Tokens, parse_error: *ParseError) !AST
The `parse_error` can be set if an error condition occurs. I concede that that's a little clumsy |
|