Sean
Sean

Reputation: 493

Global AJAX Error Handler in ember.js

I'm building an Ember application that has a lot of integration with a back-end API, so I'd like to set up a global AJAX error handler to display to the user if AJAX requests fail. How do I set up a global AJAX error handler in ember.js?

So far, I have an errorController:

MyApplication.ErrorController = Ember.ObjectController.extend({
    errorTitle: '',
    errorDescription: '',
    actions: {
        backToHome: function() {
            this.transitionToRoute('home');
        }
    }
});

And I'm trying to use jQuery's ajaxError function to capture an AJAX failure:

Ember.$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    var errorController = MyApplication.controllerFor('error');
    errorController.set('errorHeading', 'AJAX error');
    errorController.set('errorDescription', jqXHR.responseText); //server will return the error description
    MyApplication.transitionToRoute('error');
});

However, controllerFor doesn't exist in the MyApplication variable. I'm not sure what other way to access ErrorController since the error function is completely out of the scope of the Ember application.

Upvotes: 0

Views: 594

Answers (1)

Sean
Sean

Reputation: 493

I doubt this is the proper Ember way to do things, but I ended up solving this issue by using the __container__.lookup function in MyApplication:

Ember.$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    var errorController = MyApplication.__container__.lookup('controller:error');
    errorController.set('errorHeading', 'AJAX error');
    errorController.set('errorDescription', jqXHR.responseText); //server will return the error description
    errorController.transitionToRoute('error');
});

Upvotes: 0

Related Questions