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/tests/phpunit/tests/rest-api/rest-server.php

    r49925 r50150  
    408408        $error   = new WP_Error( $code, $message );
    409409
    410         $response = rest_get_server()->error_to_response( $error );
     410        $response = rest_convert_error_to_response( $error );
    411411        $this->assertInstanceOf( 'WP_REST_Response', $response );
    412412
     
    425425        $error   = new WP_Error( $code, $message, array( 'status' => 400 ) );
    426426
    427         $response = rest_get_server()->error_to_response( $error );
     427        $response = rest_convert_error_to_response( $error );
    428428        $this->assertInstanceOf( 'WP_REST_Response', $response );
    429429
     
    444444        $error->add( $code2, $message2, array( 'status' => 403 ) );
    445445
    446         $response = rest_get_server()->error_to_response( $error );
     446        $response = rest_convert_error_to_response( $error );
    447447        $this->assertInstanceOf( 'WP_REST_Response', $response );
    448448
     
    455455        $this->assertSame( $message2, $error->errors[ $code2 ][0] );
    456456        $this->assertSame( array( 'status' => 403 ), $error->error_data[ $code2 ] );
     457    }
     458
     459    /**
     460     * @ticket 46191
     461     */
     462    public function test_error_to_response_with_additional_data() {
     463        $error = new WP_Error( 'test', 'test', array( 'status' => 400 ) );
     464        $error->add_data( 'more_data' );
     465
     466        $response = rest_convert_error_to_response( $error );
     467        $this->assertSame( 400, $response->get_status() );
     468        $this->assertEquals( 'more_data', $response->get_data()['data'] );
     469        $this->assertEquals( array( array( 'status' => 400 ) ), $response->get_data()['additional_data'] );
    457470    }
    458471
Note: See TracChangeset for help on using the changeset viewer.