10

I'm a bit confused about how errors are handled in Wordpress's REST API. In their examples, they suggest using WP_Error to return errors, but WP_REST_Response has the HTTP status code as a second parameter, which makes it shorter and somewhat cleaner to my taste.

So I'm comparing this way of returning an error:

return new WP_REST_Response(array('error' => 'Error message.'), 400);

With this one:

return new WP_Error('rest_custom_error', 'Error message.', array('status' => 400));

With the first option, I can have just the error text in my response and it's enough for me. So the response would look like so:

{"error":"Error message."}

With the second one it's more detailed:

{"code":"rest_custom_error","message":"Error message.","data":{"status":403}}

But I also need to specify the error code (first parameter), which doesn't give any advantage to my front-end implementation. Other than the syntax, I'm curious about differences in performance, security and future-proof factors.

So is there any reason to prefer one over the other than personal preferences?

Nmk
  • 1,281
  • 2
  • 14
  • 25
Dmitry Gamolin
  • 934
  • 1
  • 12
  • 29

2 Answers2

6

I do as follows:

WP_REST_Response // Used when endpoint code runs just fine but needs to 
                 // tell the client about some other downstream error (e.g. 4xx)
WP_Error // Used when endpoint code has an issue and needs to tell you
         // it didn't compute or couldn't find resources etc (e.g. 5xx)
ed2
  • 1,457
  • 1
  • 9
  • 26
1

As far as I can tell, WordPress changes the status codes of the responses in unpredictable ways. This is dumb. For instance, if you create a WP_REST_RESPONSE with status 400, it actually sends it as status 200 with "status:400" as data in the body.

What I do: Just use PHP response functions:

http_response_code(400);
exit;

If you tell me I'm wrong, please explain the benefit of using these two function wrappers. I see the benefit if you work for Automattic and are creating regressions in core itself. If you're a plugin or theme dev, [and you're assuming core works] these functions should be avoided as having no use.

vancoder
  • 178
  • 9
John Dee
  • 539
  • 4
  • 14
  • 2
    To return the right response code, just do : `return new WP_REST_Response(array(), 400);` If I check in the DevTools, I see a "400 Bad Request". So it works. – JPG Dev Feb 08 '23 at 14:51
  • Not sure if this was true in the past, but I just tested returning `new WP_REST_Response(array(), 400);` from an endpoint the HTTP code is set correctly. Tested making a request with `curl -I` – Leo Germani May 12 '23 at 20:48