kach / nearley

📜🔜🌲 Simple, fast, powerful parser toolkit for JavaScript.
https://nearley.js.org
MIT License
3.57k stars 231 forks source link

Distinguish types of exceptions #583

Open Lysxia opened 3 years ago

Lysxia commented 3 years ago

In feed(), there are two places throwing exceptions: one when the lexer fails, and one when the parser fails. However both just throw an Error() (in particular, the former swallows the lexer's exception), so it's a little tricky to distinguish them. One way is to check whether the exception carries a .token field. Another is to query the lexer out of band.

I propose a more direct alternative: make those exceptions two subclasses of Error. Furthermore, it would be nice if the lexer's own exception were completely preserved in some form so that the lexer doesn't have to store it separately. What do you think of that?


Also, what is this line err.token = e.token doing? As far as I can tell, nowhere outside of the parser is there any exception thrown with the .token field set, and the documentation on custom lexers does not mention anything about exceptions.

https://github.com/kach/nearley/blob/master/lib/nearley.js#L297