Where can I place global ajax error handling in Ember?

In my application adapter, I am returning error codes based on ajax errors. I process them in the application route error method. This works great if I access the route by reference. But if I update the route or just type the URL, my application error handler is not called. Is there a place where I can put this error handling, which will be guaranteed to run every time? I really don't want to implement the same "if 401, show login" code on 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 almost worked for me. The main problem I hit was this.send ('showLogin') did not come across when updating or deleting the url. Change this to a transition. Works great:

 import Ember from 'ember'; export default Ember.Route.extend(ApplicationRouteMixin, { actions: { error: function(reason) { if (reason === 401) { this.transitionTo('login'); } }, ... 
+6
source share
2 answers

You can create an application adapter and then expand each adapter and use the 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({ }); 
+1
source

If you are using RSVP promises then

 Ember.RSVP.on('error', function(error) { // ... }); 

Or if you use plain jQuery xhr

 $(document).ajaxError(function(evt, jqXHR) { // ... }); 
0
source

Source: https://habr.com/ru/post/984712/


All Articles