rest_convert_error_to_response() WordPress Function

The rest_convert_error_to_response() function is used to convert a WP_Error object into a JSON-encoded WP_REST_Response object. This is useful for creating custom error messages and/or error codes in the REST API.

rest_convert_error_to_response( WP_Error $error ) #

Converts an error to a response object.


Description

This iterates over all error codes and messages to change it into a flat array. This enables simpler client behaviour, as it is represented as a list in JSON rather than an object/map.


Top ↑

Parameters

$error

(WP_Error)(Required)WP_Error instance.


Top ↑

Return

(WP_REST_Response) List of associative arrays with code and message keys.


Top ↑

Source

File: wp-includes/rest-api.php

function rest_convert_error_to_response( $error ) {
	$status = array_reduce(
		$error->get_all_error_data(),
		static function ( $status, $error_data ) {
			return is_array( $error_data ) && isset( $error_data['status'] ) ? $error_data['status'] : $status;
		},
		500
	);

	$errors = array();

	foreach ( (array) $error->errors as $code => $messages ) {
		$all_data  = $error->get_all_error_data( $code );
		$last_data = array_pop( $all_data );

		foreach ( (array) $messages as $message ) {
			$formatted = array(
				'code'    => $code,
				'message' => $message,
				'data'    => $last_data,
			);

			if ( $all_data ) {
				$formatted['additional_data'] = $all_data;
			}

			$errors[] = $formatted;
		}
	}

	$data = $errors[0];
	if ( count( $errors ) > 1 ) {
		// Remove the primary error.
		array_shift( $errors );
		$data['additional_errors'] = $errors;
	}

	return new WP_REST_Response( $data, $status );
}


Top ↑

Changelog

Changelog
VersionDescription
5.7.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More