From 07ad6efdf7157d22424496d39d8c5635f28ecfbb Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Sun, 31 Oct 2021 06:06:02 +0000 Subject: [PATCH] REST API: Send a 500 status code when JSON encoding fails. Previously, a 200 status code would be sent despite the 500 status code present in the response body. Props hermpheus, lalitjalandhar. Fixes #53056. git-svn-id: https://develop.svn.wordpress.org/trunk@51960 602fd350-edb4-49c9-b593-d223f7449a82 --- .../rest-api/class-wp-rest-server.php | 1 + tests/phpunit/includes/spy-rest-server.php | 9 ++++++++ tests/phpunit/tests/rest-api/rest-server.php | 22 +++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/src/wp-includes/rest-api/class-wp-rest-server.php b/src/wp-includes/rest-api/class-wp-rest-server.php index 55f0ce6fc8..e2999f7c82 100644 --- a/src/wp-includes/rest-api/class-wp-rest-server.php +++ b/src/wp-includes/rest-api/class-wp-rest-server.php @@ -497,6 +497,7 @@ class WP_REST_Server { $json_error_message = $this->get_json_last_error(); if ( $json_error_message ) { + $this->set_status( 500 ); $json_error_obj = new WP_Error( 'rest_encode_error', $json_error_message, diff --git a/tests/phpunit/includes/spy-rest-server.php b/tests/phpunit/includes/spy-rest-server.php index 596117347c..5bfd1d2dba 100644 --- a/tests/phpunit/includes/spy-rest-server.php +++ b/tests/phpunit/includes/spy-rest-server.php @@ -6,6 +6,7 @@ class Spy_REST_Server extends WP_REST_Server { public $sent_body = ''; public $last_request = null; public $override_by_default = false; + public $status = null; /** * Gets the raw $endpoints data from the server. @@ -37,6 +38,14 @@ class Spy_REST_Server extends WP_REST_Server { $this->sent_headers[ $header ] = $value; } + /** + * Stores last set status. + * @param int $code HTTP status. + */ + public function set_status( $status ) { + $this->status = $status; + } + /** * Removes a header from the list of sent headers. * diff --git a/tests/phpunit/tests/rest-api/rest-server.php b/tests/phpunit/tests/rest-api/rest-server.php index 03d1cf21fa..30977958fa 100644 --- a/tests/phpunit/tests/rest-api/rest-server.php +++ b/tests/phpunit/tests/rest-api/rest-server.php @@ -2022,6 +2022,28 @@ class Tests_REST_Server extends WP_Test_REST_TestCase { $this->assertArrayHasKey( 'https://api.w.org/active-theme', $index->get_links() ); } + /** + * @ticket 53056 + */ + public function test_json_encode_error_results_in_500_status_code() { + register_rest_route( + 'test-ns/v1', + '/test', + array( + array( + 'methods' => \WP_REST_Server::READABLE, + 'callback' => function() { + return new \WP_REST_Response( INF ); + }, + 'permission_callback' => '__return_true', + 'args' => array(), + ), + ) + ); + rest_get_server()->serve_request( '/test-ns/v1/test' ); + $this->assertSame( 500, rest_get_server()->status ); + } + public function _validate_as_integer_123( $value, $request, $key ) { if ( ! is_int( $value ) ) { return new WP_Error( 'some-error', 'This is not valid!' );