Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the error response in Backbone's model.save error callback?

Backbone's error callback on model.save only takes two arguments error: function(model, response){}. In my application, if optimistic locking fails a 409 conflict status is set (which is easily retrievable). However, the server also sends a custom error message detailing the problem.

Now the server sends an updated JSON response with the updated model along with an error message stating what the problem was. It seems, backbone suppresses this error. As per jquery's error callback the signature is error(jqXHR, textStatus, errorThrown). Seems Backbone discards the last part and thus I can't seem to get my hands on the server's custom response.

Is this a good practice? I really don't wish to duplicate backbone's functionality of save just to have access to the errorThrown parameter. Is there a seamless way to access the errorThrown? Or is it a better practice to NOT have the server send a custom response, only the code and have the client build the response for viewing??

like image 651
PhD Avatar asked Dec 16 '25 22:12

PhD


1 Answers

Backbone passes 2 parameters into both the success and error cases. The first is the model you are saving on and the second is the response from the server. If the response is in JSON, you can access it by calling response.responseJSON

this.model.save(null, {
    success: function(model, response) {
        console.model(response);
    },
    error: function (model, response) {
        console.log(response.responseJSON);
    }
});
like image 113
Peter Graham Avatar answered Dec 20 '25 01:12

Peter Graham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!