Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage of server error response with backbone

I would like to know the best way to manage server error response on new, update or delete models. At this moment the server returns a http status code # 400. But the default error handler in Backbone is not showing the errors.

How can i show these errors?

Is it ok that the server returns http error headers when a server side validation fails? (Maybe is better return a success response with a status='ERROR' message)

like image 894
Jaime Rivera Avatar asked Aug 27 '12 19:08

Jaime Rivera


1 Answers

If you're returning an http status other than 2XX, you're already half way done with the job. :-) Basically, what you can do is send back anything you want back as the response.

For example, you might just send back something like this:

// Send back http status 500
echo 'Could not save, server error';

The 500 status will trigger the Backbone error callback and your response is a jqXHR object. In the above example you can get the message by doing something like this in your error callback.

model.save({},{
    error: function(model, response) {
        console.log(response.responseText);
    }
});

This is the simplest way to get back some data/message about the error that happened server side. You can of course, create more sophisticated data to be returned from the server:

// I'm using SLIM RESTful framework...
$dataOut = array('error'=>'Validation type', 'message'=>'Did not validate');
$response->body(json_encode($dataOut));

In the same fashion, you can access that response like so:

model.save({},{
    error: function(model, response) {
        var responseObj = $.parseJSON(response.responseText);
        console.log('Type: ' + responseObj.error + ' Message: ' + responseObj.message);
    }
});

Or something along those lines.

Because the response passed into your error callback is the jqXHR object, you have full access to all of its properties that you may want to use:

E.g.
response.readyState
response.status
response.statusText // etc.

Backbone only needs the http status returned from the server to do its thing.

like image 78
jmk2142 Avatar answered Nov 06 '22 00:11

jmk2142