How can I detect that an input stream contains an incomplete json #4347
-
I've seen some questions with similar cases, and tried to go through the documentation, but couldn't quite find a clean solution. My issue is I have a stream, which could contain several json objects. I am waiting for data to come in, and each time a chunk is received I try to parse it. When I find a json object, I remove it from the stream and move on to the next. There are two failure cases I care about: 1: if there's something that's not valid json, I should discard the stream. I expect this to not happen but I can't trust the stream to not be corrupted at some point. 2: if a chunk only contains part of a json, I need to wait for the next chunk (or several) to be able to complete parsing. In this case, I can ignore the error and try again later. I've seen it suggested to use accept() to check, but that would treat both the above cases the same. There could be a situation where some broken json is sent, and the program just keeps waiting for more and more chunks to arrive even though the parse will never succeed. The parse exception distinguishes between these two cases, reporting "unexpected end of input" for case 2, which is what I need. My current approach is to catch the exception and search the what() string for the error:
This works, but I'm not a fan of "stringly typed" values. I'd rather have an actual sub-error value to check, seeing as all the logic to distinguish the error cases is already in place. Is there a way to get this other than parsing the error string? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You could check the |
Beta Was this translation helpful? Give feedback.
You could check the
id
member of theparse_error
exception to be110
which is the code for general parse errors including the "unexpected end of input". Then you could also check thebyte
member which indicates the error position. This should point to the last byte of the input in case of an "unexpected end of input" error.