Reputation: 105
I'm trying to write a handler for all failed routes in my Ember application.
The documentation here seems to suggest that I can make a ErrorRoute on my App object which will automatically be transitioned to when routing on another route failed. I want to use this to redirect the user to a login page if the reason for the routing failure is due to an authentication problem (such as token timeout).
The problem I have is that inside the ErrorRoute I don't seem to have any way to access the error returned by the route that failed. I want to check for sure that it was an authentication error before redirecting them to the login screen and I'm not sure how to do that.
Here is what I wrote for testing:
App.ErrorRoute = Ember.Route.extend({
activate: function() {
console.log("MODEL A", this.modelFor('error'));
setInterval(function() {
console.log("MODEL B", this.modelFor('error'));
}.bind(this), 1000);
}
});
When the route is activated, the console logs MODEL A undefined
as it tries to access the model for the App.ErrorController which isn't set yet for some reason. After a second the MODEL B
console log fires and the error model has been set up.
If I can't access the error in the Route's activate
method then where can I access it? Presumably I'm not supposed to wrap my logic in a timeout.
Upvotes: 2
Views: 131
Reputation: 5535
The error model is passed to the error route's renderTemplate(controller, model)
method.
If you don't care about landing on a *.error
route substate, if you're going to redirect anyway, @ppcano's answer is sufficient. But sometimes you want to encapsulate all error handling in a dedicated error route object. renderTemplate
then is your place to handle things.
I agree though, it would be nice if its hooks had the correct modelFor(...)
available.
Upvotes: 0
Reputation: 2861
You could manage the error in any route of your current active hierarchy.
Normally, you setup your error handler at the application route to perform your app error logic.
App.AccountRoute = Ember.Route.extend({
afterModel: function() {
return new Em.RSVP.Promise(function(resolve, reject){
throw new AuthenticatedError('error message');
});
}
});
App.ApplicationRoute = Ember.Route.extend({
actions: {
error: function(error) {
if ( error instanceof AuthenticatedError ) {
this.transitionTo('login');
} else {
// if return true, the event will bubble and transition to error
return true;
}
}
}
});
http://emberjs.jsbin.com/cisur/1/edit
Upvotes: 1