Using WordPress ‘rest_convert_error_to_response()’ PHP function

The rest_convert_error_to_response() WordPress PHP function converts an error to a response object.

Usage

$result = rest_convert_error_to_response( $error );

Parameters

  • $error (WP_Error) – Required. The WP_Error instance to be converted.

More information

See WordPress Developer Resources: rest_convert_error_to_response()

Examples

Converting a WP_Error instance to a WP_REST_Response

This example demonstrates how to convert a WP_Error instance to a WP_REST_Response using rest_convert_error_to_response().

$error = new WP_Error( 'invalid_request', 'Invalid request' );
$response = rest_convert_error_to_response( $error );

Handling a REST API request error

This example demonstrates how to handle an error in a REST API request by converting it to a response using rest_convert_error_to_response().

function handle_rest_request( WP_REST_Request $request ) {
  if ( empty( $request['param'] ) ) {
    $error = new WP_Error( 'missing_param', 'Missing required parameter' );
    return rest_convert_error_to_response( $error );
  }

  // Process the request and return the response
}

Custom REST API endpoint with error handling

This example shows how to create a custom REST API endpoint that handles errors using rest_convert_error_to_response().

function custom_rest_endpoint( WP_REST_Request $request ) {
  if ( ! user_can( get_current_user_id(), 'manage_options' ) ) {
    $error = new WP_Error( 'permission_denied', 'You do not have permission to access this resource' );
    return rest_convert_error_to_response( $error );
  }

  // Process the request and return the response
}

add_action( 'rest_api_init', function () {
  register_rest_route( 'custom/v1', '/resource', array(
    'methods' => 'GET',
    'callback' => 'custom_rest_endpoint',
  ) );
} );

Converting a custom error to a response

This example demonstrates how to convert a custom error to a WP_REST_Response using rest_convert_error_to_response().

function custom_error_handler() {
  $custom_error = new WP_Error( 'custom_error', 'A custom error occurred' );
  $response = rest_convert_error_to_response( $custom_error );

  // Handle the response
}

Handling a form submission error with REST API

This example demonstrates how to handle a form submission error with the REST API using rest_convert_error_to_response().

function process_form_submission( WP_REST_Request $request ) {
  if ( empty( $request['form_data'] ) ) {
    $error = new WP_Error( 'empty_form_data', 'Form data is empty' );
    return rest_convert_error_to_response( $error );
  }

  // Process the form submission and return the response
}

add_action( 'rest_api_init', function () {
  register_rest_route( 'custom/v1', '/submit-form', array(
    'methods' => 'POST',
    'callback' => 'process_form_submission',
  ) );
} );