Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global error handler for backbone.js ajax requests

Is there way to bind one error handler for ajax requests that performs by backbone.js?

My situation: I can get 401 (Unauthorized) at any time, so I need to show login popup.

like image 881
Plastic Rabbit Avatar asked May 27 '11 09:05

Plastic Rabbit


1 Answers

Backbone's sync triggers an 'error' event when errors occur. So one approach you could take is to extend Backbone's Model and Collection objects to add these add-on error checks. It would look something like this:

ErrorHandlingModel = Backbone.Model.extend({      initialize: function(attributes, options) {         options || (options = {});         this.bind("error", this.defaultErrorHandler);         this.init && this.init(attributes, options);     },      defaultErrorHandler: function(model, error) {         if (error.status == 401 || error.status == 403) {             // trigger event or route to login here.         }     }  });  OtherModel = ErrorHandlingModel.extend({ }); 

and you would do something similar for the Collection object. I haven't tested the above, but think its pretty close. Obviously, you would choose better class names. The init method just enables subclasses to get a chance to do their own initialization.

like image 155
Bill Eisenhauer Avatar answered Sep 19 '22 22:09

Bill Eisenhauer