Adapter error when connection is lost


#1

When my application loses the internet connection, I get an error coming from the adapter and I’m not sure why it does that.

Error: Adapter operation failed
    at new Error (native)
    at Error.EmberError (http://localhost:5966/assets/vendor.js:25883:21)
    at Error.ember$data$lib$adapters$errors$$AdapterError (http://localhost:5966/assets/vendor.js:66151:50)
    at ember$data$lib$system$adapter$$default.extend.handleResponse (http://localhost:5966/assets/vendor.js:67455:16)

My application adapter looks like this:

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {
	host: config.apiUrl,

	handleResponse(status, headers, payload) {
		if (status === 422 && payload.errors) {
			return new DS.InvalidError(payload.errors);
		}

		return this._super(...arguments);
	}
});

The error action in my application route never gets triggered.

export default Ember.Route.extend({
	actions: {
		error(error, transition) {
			console.log(error, transition); //Never displayed
		}
	}
});

I’m making the call to the store in my controller.

export default Ember.Controller.extend({
	actions: {
		getUsers() {
			this.get('store').findAll('user').then((users) => {
				this.set('users', users);
			});
		}
	}
});

Any idea how to fix this error and trigger the error hook in my route?

Thanks


#2

The error hook is only triggered if the error happens in a transition (that is, if one of beforeModel, model and afterModel returns a promise and that promise is rejected).

If you want to go to the error route when your request fails, you have to do it yourself, by providing an error handler that triggers the transition. Something like this should do:

getUsers() {
  this.get('store').findAll('user').then((users) => {
    this.set('users', users);
  }, (err) => {
    // Do something if there is an error, for instance transition
    this.transitionToRoute('some.root.error');
    // or send an action to the route
    this.send('error', err);
  });
}

#3

Is there a way to handle that automatically for all the call I make to the store?


#4

Automatically I don’t know, but you could just put the code in a function you can use from anywhere.