WordPress.org

Make WordPress Core


Ignore:
Timestamp:
02/02/2021 05:26:06 PM (3 months ago)
Author:
TimothyBlynJacobs
Message:

REST API: Return detailed error information from request validation.

Previously, only the first error message for each parameter was made available. Now, all error messages for a parameter are concatenated. Additionally, the detailed error for each parameter is made available in a new details section of the validation error. Each error is formatted following the standard REST API error formatting.

The WP_REST_Server::error_to_response method has been abstracted out into a standalone function rest_convert_error_to_response to allow for reuse by WP_REST_Request. The formatted errors now also contain an additional_data property which contains the additional error data provided by WP_Error::get_all_error_data.

Props dlh, xkon, TimothyBlynJacobs.
Fixes #46191.

File:
1 edited

Legend:

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

    r49955 r50150  
    197197     *
    198198     * @since 4.4.0
     199     * @since 5.7.0 Converted to a wrapper of {@see rest_convert_error_to_response()}.
    199200     *
    200201     * @param WP_Error $error WP_Error instance.
     
    202203     */
    203204    protected function error_to_response( $error ) {
    204         $error_data = $error->get_error_data();
    205 
    206         if ( is_array( $error_data ) && isset( $error_data['status'] ) ) {
    207             $status = $error_data['status'];
    208         } else {
    209             $status = 500;
    210         }
    211 
    212         $errors = array();
    213 
    214         foreach ( (array) $error->errors as $code => $messages ) {
    215             foreach ( (array) $messages as $message ) {
    216                 $errors[] = array(
    217                     'code'    => $code,
    218                     'message' => $message,
    219                     'data'    => $error->get_error_data( $code ),
    220                 );
    221             }
    222         }
    223 
    224         $data = $errors[0];
    225         if ( count( $errors ) > 1 ) {
    226             // Remove the primary error.
    227             array_shift( $errors );
    228             $data['additional_errors'] = $errors;
    229         }
    230 
    231         $response = new WP_REST_Response( $data, $status );
    232 
    233         return $response;
     205        return rest_convert_error_to_response( $error );
    234206    }
    235207
Note: See TracChangeset for help on using the changeset viewer.