Happy day scenario: I implement WP REST API that sends JSONs to a JavaScript client, which parses it and displays the data to the user. All is fine.
What actually happens, inevitably: some WordPress code or plugin generates a PHP notice or warning, and the server is configured so that this garbage finds its way to the JSON response. (WP REST API tries to avoid that but for example if ini_set()
is disallowed by server configuration, it can still happen.)
One way to approach is to simply blame it on the users – if their servers are configured so that they send PHP notices and warnings in production it's certainly bad. However, even the core REST infrastructure tries to support users who have badly configured servers and it's my goal as well in this case.
Is there a technique established for dealing with this? I can see two ways:
- Detect in JavaScript that the response is malformed, show some error and refuse to work.
- Modify the actual JSON by adding some unique key to it on the server and let the JavaScript client work with that. For example, instead of the plain value
123
, it would be wrapped into an object like{ "__VALID__": true, "data": 123 }
and the JS code would useresponse.body.data
instead ofresponse.body
.
Or is there some other approach?
123
(valid response), it gets something likeNotice: Undefined variable...123
. The trouble is that you cannot reliably capture notices on the server and wrap them inside your JSON, I think.