Global error handler for backbone.js ajax requests

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)