Skip to content

Is it possible to embed information in errors? #572

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
hasenj opened this issue Oct 31, 2017 · 7 comments
Closed

Is it possible to embed information in errors? #572

hasenj opened this issue Oct 31, 2017 · 7 comments
Milestone

Comments

@hasenj
Copy link

hasenj commented Oct 31, 2017

For example, say I'm parsing something and I hit an unexpected character, so I do something like:

return error.invalidChar;

But I also want the error to carry information about which char was invalid.

Is there a way to do that?

@andrewrk
Copy link
Member

The suggestion for this situation is to make your own type with enum and use that.

const Result = enum {
    Ok,
    InvalidChar: usize,
};
fn parse(input: []const u8) -> Result {
    // if it works
    return Result.Ok{};
    // if it has unexpected char
    return Result.InvalidChar { position };
}

@thejoshwolfe
Copy link
Contributor

This is brushing against a general issue which is that zig error codes are used a lot like exception objects (in Java, for example), but zig error codes are missing lots of useful features of exception objects. Another missing feature that would be useful is a stack trace.

@hasenj
Copy link
Author

hasenj commented Nov 1, 2017

Thanks @andrewrk, I think that makes sense to me.

Regarding stack traces, I think it would be useful if there was a compiler function to get current line number, e.g. @lineinfo() which could return something like a struct { filename: []const u8, line: u64, col: u64 } or something like that.

Though I'm not sure how that would interact with the error enum, or if it even should.

@andrewrk
Copy link
Member

andrewrk commented Nov 1, 2017

@lineinfo() which could return something like a struct { filename: []const u8, line: u64, col: u64 } or something like that.

I agree, I was thinking along the same lines. Want to make a new issue with a proposal? We can use that to track the feature.

@hasenj
Copy link
Author

hasenj commented Nov 2, 2017

opened #577

@andrewrk andrewrk added this to the 0.3.0 milestone Nov 2, 2017
@andrewchambers
Copy link

The proposed solution will not work with errdefer though?

@andrewrk
Copy link
Member

The proposed solution will not work with errdefer though?

In this case you can populate the error data, and then return a general error such as error.SemanticAnalysisFailed. This is the strategy taken by the self hosted compiler, for example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants