gutenberg icon indicating copy to clipboard operation
gutenberg copied to clipboard

Improve the error handling for invalid JSON

Open caseymilne opened this issue 5 years ago • 3 comments

What problem does this address?

As JSON files are increasingly important (to FSE) and block development, and as there will be more manual editing of JSON going forward (post FSE going live) it is important to handle the issue of silent failure caused by JSON parsing errors. It only take one keystroke to break an FSE site. Just edit the theme.json that is parsed and controls everything, add one trailing comma, and your site is dead. Any block or Site Editor can be broken with one keystroke because JSON validation is very precise, it either validates and can be parsed or it cannot be parsed in which case the response from the PHP parsing is null. The result, everything breaks.

What is your proposed solution?

I would recommend using a TRY/CATCH approach with prominent error messaging. First we use PHP exception handling around all calls to json_decode() that are used to parse block JSON definitions and FSE theme.json files. If these cannot be parsed we aim to make this obvious to the site owner or developer through alerts and/or logging functions.

Bottom line is we should not allow a single keystroke to break a site due to a json_decode failure which can be caused so easily given users are being encouraged to manually edit JSON files. All it takes is this:

The code below pasted into any theme.json will NOT parse due to the trailing comma:

"supports": [ "valid_item": "valid_item_value", <<<< Trailing slash here means silent death. ]

Anybody that copy/pastes code into and around their JSON files will eventually make the mistake of leaving a trailing slash. For those doing this work regularly we know silent death equals JSON trailing slash, but for many millions of users it will result in hours or days of fruitless debugging.

caseymilne avatar Aug 17 '21 15:08 caseymilne

Has this still been an issue for you ? There has been some work to improve this at https://github.com/WordPress/gutenberg/pull/32404

skorasaurus avatar Dec 05 '22 20:12 skorasaurus

FWIW wp_json_file_decode() landed and both theme.json and block.json use it now, so a parse error does report the file and the actual JSON error.

One thing to keep in mind is that wp_trigger_error() that it goes through, which bails out when WP_DEBUG is off, so for most site owners it's still a silent failure.

I'd say what's left here is surfacing it outside debug mode, maybe an admin notice or a Site Health check. But if we're good with what we have, this might as well be closed.

tyxla avatar Sep 08 '26 13:09 tyxla

Closing per the previous comment.

youknowriad avatar Oct 26 '26 09:10 youknowriad