Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I put global ajax error handling in Ember?

In my application's adapter, I'm returning error codes based on ajax errors. I'm handling these in the application route's error method. This works great if I access a route via link-to. But if I refresh a route or just type the URL in, my application's error handler isn't called. Is there a place where I can put this error handling that will be guaranteed to run every time? I really don't want to implement the same "if 401, show login" code in every single route.

routes/application.js:

export default Ember.Route.extend({
  actions: {
    error: function(reason) {
        if (reason === 401) {
          alert('401');
            this.send('showLogin');
        }
    },

adapters/application.js:

import DS from 'ember-data';

export default DS.ActiveModelAdapter.extend({
    'namespace': '',
  ajaxError: function(jqXHR) {
    var error = this._super(jqXHR);
    if (jqXHR && jqXHR.status === 401) {
        return 401;
    }
    return error;
  }
});

Edit:

The above code nearly worked for me. The main issue I hit was this.send('showLogin') wasn't being caught when refreshing or hitting the URL. Changing this to a transitionTo works great:

import Ember from 'ember';

export default Ember.Route.extend(ApplicationRouteMixin, {
  actions: {
    error: function(reason) {
      if (reason === 401) {
        this.transitionTo('login');
      }
    },
    ...
like image 227
Dennis Avatar asked Apr 05 '15 20:04

Dennis


1 Answers

You can make an application adapter, and then extend every adapter from this, and use isInvalid function.

//app/adapters/application.js
import DS from 'ember-data';
import Ember from 'ember';

export default DS.JSONAPIAdapter.extend({

    isInvalid(status, headers, payload){ 
        if (status===401) {}
    },

});

//app/adapters/anotherAdapter.js

import AppAdapter from 'yourapp/adapters/application';

export default AppAdapter.extend({

});
like image 71
jesusda91 Avatar answered Oct 16 '22 22:10

jesusda91