WordPress.org

Make WordPress Core


Ignore:
Timestamp:
11/03/2016 04:04:41 AM (4 years ago)
Author:
joehoyle
Message:

REST API: Return error when JSON decoding fails.

If you send a request to the REST API with invalid JSON in body than it will now return a error. This assists developers if they accidentally send invalid JSON and wonder why their data appears to be ignored.

Props rmccue.
Fixes #38547.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/rest-api/class-wp-rest-request.php

    r39091 r39109  
    652652     *
    653653     * @since 4.4.0
     654     * @since 4.7.0 Returns error instance if value cannot be decoded.
    654655     * @access protected
     656     * @return true|WP_Error True if the JSON data was passed or no JSON data was provided, WP_Error if invalid JSON was passed.
    655657     */
    656658    protected function parse_json_params() {
    657659        if ( $this->parsed_json ) {
    658             return;
     660            return true;
    659661        }
    660662
     
    665667
    666668        if ( empty( $content_type ) || 'application/json' !== $content_type['value'] ) {
    667             return;
     669            return true;
    668670        }
    669671
     
    677679         */
    678680        if ( null === $params && ( ! function_exists( 'json_last_error' ) || JSON_ERROR_NONE !== json_last_error() ) ) {
    679             return;
     681            // Ensure subsequent calls receive error instance.
     682            $this->parsed_json = false;
     683
     684            $error_data = array(
     685                'status' => WP_Http::BAD_REQUEST,
     686                'json_error_code' => json_last_error(),
     687                'json_error_message' => json_last_error_msg(),
     688            );
     689            return new WP_Error( 'rest_invalid_json', __( 'Invalid JSON body passed.' ), $error_data );
    680690        }
    681691
    682692        $this->params['JSON'] = $params;
     693        return true;
    683694    }
    684695
     
    842853     */
    843854    public function has_valid_params() {
     855        // If JSON data was passed, check for errors.
     856        $json_error = $this->parse_json_params();
     857        if ( is_wp_error( $json_error ) ) {
     858            return $json_error;
     859        }
     860
    844861        $attributes = $this->get_attributes();
    845862        $required = array();
Note: See TracChangeset for help on using the changeset viewer.