Today I was playing with BackboneJS save/destroy methods on data models.
My JS app was binded to a MySQL db by a CakePHP (CakePower) REST layer so I have a controller implementing the CRUD methods.
This controller sends notifications using the CakePower notification system but I found a problem with this interface: no error http status was given to the response!
// the simple CakePower error notification:
$this->Session->error( 'user not found' );
This code drives standard CakePHP requests (forms, links) setting up a flashMessage, ajax and REST requests setting up a JSON response object.
The problem was all responses was given with the 200 HTTP Status code! This was a very bad mistake!
If errors was found in controller’s logic then HTTP Status needs to be configured according to the error: 404 if resource was not found or, at least, a generic 500 – Internal Server Error.
Dealing with jQuery::ajax()
The real world problem was that with 200 response status jQuery::ajax()’s error callback was never thrown!
BackboneJS Model::destroy() method implements an automation to remove destroyed model from related collections… But this automation fails without correct HTTP status!
NOW THIS BUG IS FIXED AND ALL THINGS WORKS FINE!
Customize HTTP Status Code
Default HTTP Status is 200 for: message(), confirm(), warning() methods and 404 for error() method.
You can customize this information with the status option:
$this->error( 'bad request!', null, array( 'status'=>400 ) );
$this->confirm( 'updated!', null, array( 'status'=>204 ) );
Have a nice developing experience with CakePower and BackboneJS!