Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 321 Vote(s) - 3.52 Average
  • 1
  • 2
  • 3
  • 4
  • 5
WP_REST_Response vs WP_Error

#1
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?
Reply

#2
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)
```
Reply

#3
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.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through