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:

  1. Detect in JavaScript that the response is malformed, show some error and refuse to work.
  2. 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 use response.body.data instead of response.body.

Or is there some other approach?

3 Answers
3

If you are creating classes, the first thing in the construct would be this. Or you can drop it in with an action as early as possible. Maybe plugins_loaded.

/*
     * If WP DEBUG is not on do NOT return any php warning, notices, and/or fatal errors.
     * Well If it is a fatal error then this return is FUBAR anyway...
     * We do this because some badly configured servers will return notices and warnings switch get prepended or appended to the rest response.
     */
    if( defined('WP_DEBUG') ){
        if( false === WP_DEBUG ){
            error_reporting(0);
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *