从适配器处理错误

Mep*_*ph- 3 ember.js ember-data

如何处理来自商店或适配器的restAdapter错误?现在我正在使用此代码:

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 [];
        });

    },
});
Run Code Online (Sandbox Code Playgroud)

更通用的东西会更好.谢谢

aha*_*w01 5

在整个ember数据中存在一些更复杂的错误处理之前,您可以执行以下操作以交叉方式处理网络错误:

扩展RESTAdapter以解析xhr对象的错误

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;
  }
});
Run Code Online (Sandbox Code Playgroud)

当坏事发生时,扩展存储以发布错误事件

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

在应用程序路径中捕获错误

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

  ...
});
Run Code Online (Sandbox Code Playgroud)