WordPress.org

Make WordPress Core

Opened 4 years ago

Closed 4 years ago

Last modified 4 years ago

#35028 closed defect (bug) (fixed)

WP_Error objects returned by REST API validation callbacks aren't formatted correctly

Reported by: bradyvercher Owned by: joehoyle
Milestone: 4.5 Priority: normal
Severity: normal Version: 4.4
Component: REST API Keywords: has-patch has-unit-tests
Focuses: Cc:
PR Number:

Description

Here's an example response with two missing parameters. The software_id validation callback returns a WP_Error instance, while the software_version is required, but doesn't have a validation callback defined.

{  
   "code":"rest_invalid_param",
   "message":"Invalid parameter(s): software_id (Invalid software identifier.), Invalid parameter.",
   "data":{  
      "status":400,
      "params":{  
         "0":"software_id (Invalid software identifier.)",
         "software_version":"Invalid parameter."
      }
   }
}

Attachments (1)

35028.diff (513 bytes) - added by bradyvercher 4 years ago.

Download all attachments as: .zip

Change History (7)

@bradyvercher
4 years ago

#1 @bradyvercher
4 years ago

  • Keywords has-patch added

Here's how the same response is formatted with the attached patch applied:

{  
   "code":"rest_invalid_param",
   "message":"Invalid parameter(s): Invalid software identifier., Invalid parameter.",
   "data":{  
      "status":400,
      "params":{  
         "software_id":"Invalid software identifier.",
         "software_version":"Invalid parameter."
      }
   }
}

#2 @swissspidy
4 years ago

  • Keywords needs-unit-tests added

There are couple of tests for the has_valid_params() method already. It would be good to have a test for this as well.

#3 @joehoyle
4 years ago

  • Owner set to joehoyle
  • Resolution set to fixed
  • Status changed from new to closed

In 35890:

REST API: Improve formatting of failed validation errors.

If a validation_callback returns a WP_Error it should give the same response format as if it returned false. This makes programmatically reading the validation errors better.

Props bradyvercher for initial patch.
Fixes #35028.

#4 @joehoyle
4 years ago

I updated the response format to be:

{  
   "code":"rest_invalid_param",
   "message":"Invalid parameter(s): software_id, software_version",
   "data":{  
      "status":400,
      "params":{  
         "software_id":"Invalid software identifier.",
         "software_version":"Invalid parameter."
      }
   }
}

This makes it a bit more readable too. Also, added unit tests for returning a WP_Error from the validate callback. Thanks bradyvercher!

#5 @bradyvercher
4 years ago

Very cool. Thanks for the improvements!

#6 @swissspidy
4 years ago

  • Keywords has-unit-tests added; needs-unit-tests removed
  • Milestone changed from Awaiting Review to 4.5
Note: See TracTickets for help on using tickets.