Tomáš Král Tomáš Král -4 years ago 36
JSON Question

How to handle parser errors

I'm writing a JSON parser and I have trouble coming up with good design for the error handling.
Let's say that at some point, the lexical analyser founds a token with a lexical error in it. How should it react ? Should it stop right away or continue to the end of the string ? How do parser generally handle lexical errors ?

Answer Source

In the case of lexical errors, you should go on evalutating the whole string. Showing more than an error at the time could be helpful.

In case of syntax errors there are two ways:

  1. Stop everything at the first error.
  2. Go on looking for a safe sequence of tokens.

Safe sequences are sentences language-dependent which should be valid indipendently from the context. This does not fix the error itself, but allow the parser to show up other eventual errors (it's the behaviour of compilers. In case there are multiple errors, they can detect and notify most of them).

A safe sequence in JSON could be, for example, a correct object definition. Something like this (EBNF):

\{ <key>:<value>[, <key>:<value>] \}

I hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download