Meph-
Meph-

Reputation: 677

Error handling from adapter

how is possible handle restAdapter errors from store or adapter? Now I am using this code:

App.ApplicationRoute = Ember.Route.extend({
    model: function(){
        var self = this;
        return this.store.find('item').then(function(data){
            return data;
        }, function (error){
            console.log('error');
            return [];
        });

    },
});

It would be better something more general. Thanks

Upvotes: 3

Views: 1198

Answers (1)

ahaurw01
ahaurw01

Reputation: 1202

Until there is some more sophisticated error handling throughout ember data, you could do something like the following to handle network errors in a cross-cutting way:

Extend the RESTAdapter to parse errors from the xhr object

App.ApplicationAdapter = DS.RESTAdapter.extend({
  ajaxError: function (jqXHR) {
    jqXHR = this._super(jqXHR) || {status : 'unknown'};
    var error;
    if (jqXHR.status === 404) {
      error = 'not_found';
    } else if (...) {
      ...
    } else {
      error = 'dunno';
    }
    return error;
  }
});

Extend the store to publish error events when bad things happen

App.Store = DS.Store.extend(Ember.Evented, {
  recordWasError: function (record, reason) {
    this._super.apply(this, arguments);
    this.trigger('error', reason);
  }
});

Catch the error in your Application Route

App.ApplicationRoute = Ember.Route.extend({
  setupController: function () {
    this.get('store').on('error', function (error) {
      // Do something with the error
      console.error(error);
    });
  },

  ...
});

Upvotes: 5

Related Questions