Opened 10 years ago
Closed 10 years ago
#28978 closed enhancement (fixed)
wp_send_json_error() should support WP_Error objects
Reported by: | danielbachhuber | Owned by: | paulschreiber |
---|---|---|---|
Milestone: | 4.1 | Priority: | normal |
Severity: | normal | Version: | |
Component: | General | Keywords: | good-first-bug has-patch commit |
Focuses: | Cc: |
Description
It would be nice if I could just pass my WP_Error
object directly to wp_send_json_error()
Related #28523
Attachments (2)
Change History (12)
#2
@
10 years ago
+1. The way we're doing it with the REST API might be relevant too; basically we return an array of objects with both code
and message
properties.
#3
@
10 years ago
In the attached patch, I tried to emulate what @rmmcue did.
wp_send_json_error()
calls is_wp_error()
on the parameter it was passed. If true, it iterates over the object and sets $result['data']
to the just-created array.
#5
@
10 years ago
- Owner set to paulschreiber
- Status changed from new to assigned
Looks like those array casts can be dropped without an issue. (Yes, WP_Error also has a seemingly unnecessary array cast inside it.)
#7
@
10 years ago
- Keywords commit added
- Milestone changed from Future Release to 4.1
This looks good to me. Anyone else?
Not sure if intentional, but I think I agree with omitting error data. Codes and messages are simple strings, while error data can be basically anything and that may not translate well to JSON. In core, the data is a another WP_Error in some cases (like in updates).
We can always add error data later as it'd be just another key in the object. Just thinking about forwards compatibility.
#8
@
10 years ago
Any chance we can move the WP_Error stuff out to a separate function? That way we can use it in the REST API easily (wp_send_json_error
itself is a no-go, as it isn't re-entrant).
(Also, we could consider adding a filter there in case someone does want to add the data back for debugging or similar.)
I like this. I think it should result in 'code', 'message', and 'data' keys. We already use 'message' keys in a few places for wp_send_json_error().
However, WP_Error can have more than one code/message pair. At that point, what should happen?
The problem with the fourth one is it would result in a different way of fetching a code/message for a single WP_Error versus a multiple WP_Error. Unless we make it so a WP_Error is always an array (so you'd always have to ask for the 0'th value), which seems annoying.
Based on the fact that WP_Error get_error_code() does return the first code (same for message, etc.), and then there's a separate get_error_codes() etc., I'd think that point 3 makes the most sense.