I want my Emberjs application to handle HTTP Status Unauthorized (401).
The application uses ember-data to integrate a JSON API (Rails).
The client layer (Emberjs) should redirect to a Emberjs view/template prompting for login, when receiving HTTP Status Unauthorized (401).
How can I do this for the entire application?
I was researching on the same topic and looks like the information here is a little bit outdated. Using Ember 1.7.0, you should handle the error in the route. If you want to apply this to the whole app, you should add it to your ApplicationRoute
class, like so
// app/routes/application.js
import Ember from 'ember';
var ApplicationRoute = Ember.Route.extend({
actions: {
error: function (error, transition) {
// Handle the error here
if (error && error.status === 401) {
return this.transitionTo('login');
}
}
}
});
export default ApplicationRoute;
This is the same way as the documentation describes it: read here
Update: In newer versions of Ember and Ember Data, the error object structure will be a little different. The status will be a string, contained within an error object, within an errors array:
actions: {
error: function(error, transition) {
if (error.errors[0].status === '401') {
this.transitionTo('sign-in');
}
}
}
I've struggled with the same problem. I've succesfully implemented the following hack.
window.App = Em.Application.extend
ready: ->
$(document).ajaxError( (event, request, settings) =>
if request.status == 401 && !["/profile", "/users/sign_in.json"].contains(settings.url)
controller = App.__container__.lookup('controller:application')
controller.transitionToRoute('sign_in' )
)
The idea is to catch a jQuery ajaxError event. In the event you can check witch the type of error (.e.g. request.status == 401), url that caused the error (e.g. settings.url) and based on that information you can decide what to do.
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With