assemblyscript-json icon indicating copy to clipboard operation
assemblyscript-json copied to clipboard

How to catch JSON parse errors?

Open trieloff opened this issue 4 years ago • 2 comments

Is there a way to verify that a given input is indeed valid JSON?

I'm able to guard against the parsed value not being the object I expect, but not against it not being JSON at all:

let body = <JSON.Value>JSON.parse(text);
  if (body != null && body.isObj) {

trieloff avatar May 27 '21 17:05 trieloff

Good question. We should have better error handling. This is a larger issue with AS since there isn't really error handling just aborting. Perhaps JSON.parse should return an Result type.

willemneal avatar Jul 01 '21 14:07 willemneal

An alternative with one less level of type wrapping would be to introduce a JSON.Error subtype of JSON.Value, this would not break backwards compatibility and all code that is already checking for the return type with isObj would work as before and could add an else if branch for the isError case.

trieloff avatar Jul 02 '21 08:07 trieloff