Make WordPress Core

Opened 5 weeks ago

Last modified 12 days ago

#58255 new enhancement

wp_send_json_error should respect error state passed in WP_Error.

Reported by: spacedmonkey's profile spacedmonkey Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Administration Keywords: good-first-bug has-patch
Focuses: Cc:


WP_Error objects support setting the error state. This is used heavily in the REST API. The function wp_send_json_error supports error status code and passing WP_Error as an argument. The wp_send_json_error function could respect the status code in WP_Error.

Change History (5)

#1 @erichmond
3 weeks ago

I'm happy to look at this, can I get some more context just so I can replicate it easily with out going down the wrong track?

I'm guessing this isn't just a simple ajax call and to replicate it and I'll need to trigger WP_Error through a REST API route?

#2 @rohitmathur7
3 weeks ago

I looked into this and this is my analysis:


If we pass WP_Error as an argument in the wp_send_json_error() then the status code set in the WP_Error is not set as the status code in the wp_send_json_error().


I am using this way to pass the WP_Error in the wp_send_json_error():

$error_message = 'new error';
$error         = new WP_Error( 'error_code', $error_message, array( 'status' => 401 ) );
return wp_send_json_error( $error );

After applying changes to the code I was able to get this response:

If this works I can provide the patch for this.

Please correct me if I am going in the wrong direction with this.

This ticket was mentioned in PR #4496 on WordPress/wordpress-develop by rohitmathur-7.

13 days ago

  • Keywords has-patch added

Set the status code set in WP_Error as the status code if it is null.

  • If we pass WP_Error in the wp_send_json_error() function, then the status code set in the WP_Error object was not getting set as the status code.
  • So I am checking if the status code is set in the wp_send_json_error(), and If not then setting the status code of the WP_Error object as the status code in the wp_send_json_error().

Trac ticket:

#4 @spacedmonkey
12 days ago

Love the thoughts of @danielbachhuber on this one.

#5 @danielbachhuber
12 days ago

I'm not opposed to it, but I'm not sure how much value it provides.

One backwards compat concern: If someone is already passing a WP_Error object into wp_send_json_error(), this would change the behavior.

Additionally, 'status' is a magical property of REST API errors. If we were to introduce this new behavior, we may want to formalize that in some way.

Note: See TracTickets for help on using tickets.