REST API: Return 409 status when attempting to create an existing term.

Fixes an issue where submitting a well-formed request to create a term inappropriately returns a 500 error status if that term already exists.
HTTP 5xx error codes should be reserved for unexpected server errors, so "409 Conflict" is a more appropriate response.

Props alibasheer, guzzilar, shooper.
Fixes #41370.



git-svn-id: https://develop.svn.wordpress.org/trunk@41737 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
K. Adam White 2017-10-04 16:23:33 +00:00
parent acf9fa4524
commit dd92141f54
2 changed files with 16 additions and 0 deletions

View File

@ -405,6 +405,7 @@ class WP_REST_Terms_Controller extends WP_REST_Controller {
if ( $term_id = $term->get_error_data( 'term_exists' ) ) {
$existing_term = get_term( $term_id, $this->taxonomy );
$term->add_data( $existing_term->term_id, 'term_exists' );
$term->add_data( array( 'status' => 409 ) );
}
return $term;

View File

@ -602,6 +602,21 @@ class WP_Test_REST_Categories_Controller extends WP_Test_REST_Controller_Testcas
$this->assertEquals( 'so-awesome', $data['slug'] );
}
/**
* @ticket 41370
*/
public function test_create_item_term_already_exists() {
wp_set_current_user( self::$administrator );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories' );
$request->set_param( 'name', 'test' );
$response = $this->server->dispatch( $request );
$this->assertEquals( 201, $response->get_status() );
$response = $this->server->dispatch( $request );
$this->assertEquals( 409, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( 'term_exists', $data['code'] );
}
public function test_create_item_invalid_taxonomy() {
wp_set_current_user( self::$administrator );
$request = new WP_REST_Request( 'POST', '/wp/v2/invalid-taxonomy' );