Make WordPress Core


Ignore:
Timestamp:
02/13/2024 09:55:38 AM (16 months ago)
Author:
spacedmonkey
Message:

REST API: Improve error handling in REST meta fields

This update modifies the error handling mechanism in the REST API meta fields functionality. Instead of halting execution and returning on the first encountered error, it now collects all errors in a WP_Error object and continues execution. Thus, this enhancement enables handling and displaying of multiple errors in a single response, improving the debugging process.

Props TimothyBlynJacobs, spacedmonkey, hellofromTonya, oglekler.
Fixes #48823.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/rest-api/rest-post-meta-fields.php

    r56745 r57611  
    30973097
    30983098    /**
     3099     * @ticket 48823
     3100     */
     3101    public function test_multiple_errors_are_returned_at_once() {
     3102        $this->grant_write_permission();
     3103        register_post_meta(
     3104            'post',
     3105            'error_1',
     3106            array(
     3107                'single'       => true,
     3108                'show_in_rest' => array(
     3109                    'schema' => array(
     3110                        'enum' => array( 'a', 'b' ),
     3111                    ),
     3112                ),
     3113            )
     3114        );
     3115        register_post_meta(
     3116            'post',
     3117            'error_2',
     3118            array(
     3119                'single'       => true,
     3120                'show_in_rest' => array(
     3121                    'schema' => array(
     3122                        'minLength' => 1,
     3123                    ),
     3124                ),
     3125            )
     3126        );
     3127
     3128        $request = new WP_REST_Request( 'PUT', '/wp/v2/posts/' . self::$post_id );
     3129        $request->set_body_params(
     3130            array(
     3131                'meta' => array(
     3132                    'error_1' => 'c',
     3133                    'error_2' => '',
     3134                ),
     3135            )
     3136        );
     3137        $response = rest_do_request( $request );
     3138        $error    = $response->as_error();
     3139        $this->assertWPError( $error );
     3140        $this->assertContains( 'meta.error_1 is not one of a and b.', $error->get_error_messages() );
     3141        $this->assertContains( 'meta.error_2 must be at least 1 character long.', $error->get_error_messages() );
     3142    }
     3143
     3144    /**
    30993145     * Internal function used to disable an insert query which
    31003146     * will trigger a wpdb error for testing purposes.
Note: See TracChangeset for help on using the changeset viewer.