7
votes

Any thoughts on handling 401 errors?

In the application initializer I'm deferring readiness and fetching the current user via ember-data. If I receive a 401 the app dies and becomes unusable. I'd like to handle this error, and then advancereadiness. I cant seem to find a workaround for this. Any info would be appreciated!

Gist here: https://gist.github.com/unknpwn/6126462

I noticed there was a similar topic here, but it seems to be out of date.

2

2 Answers

2
votes

Application.initializer is not the correct place to put this logic. It is synchronous and it's purpose is to do things like adding custom objects to the IOC container, etc. This code is better suited in the model hooks of ApplicationRoute.

App.ApplicationRoute = Ember.Route.extend({
  beforeModel: function() {
    return App.User.find({ filter: "authenticated" });
  },
  setupController: function(controller, model) {
    controller.set('loggedIn', true);
    controller.set('currentUser', model);// or some property of that model
  },
  events: function() {
    error: function(err) {
      // error handler called in case of an error.
      // show the error message to user here
      // or transition to another route
    }
  }
});
4
votes

The previous answer is outdated. In current Ember version (1+) events are deprecated and you should use actions object (instead of function).

Ember example:

App.ApplicationRoute = Ember.Route.extend({
  actions: {
    error: function(err) {
      // error handler called in case of an error.
      // show the error message to user here
      // or transition to another route
    }
  }
});

Ember CLI example:

import Ember from 'ember';

export default Ember.Route.extend({
  actions: {
    error: function(err) {
      // error handler called in case of an error.
      // show the error message to user here
      // or transition to another route
    }
  }
});

With these action handlers the error will bubble nicely to the main application route if you don't stop it before in your route.