ember.js - 来自适配器的错误处理

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

    },
});

最好是更通用的东西。谢谢

最佳答案

在整个 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;
  }
});

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

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

在您的应用程序路由中捕获错误

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

  ...
});

关于ember.js - 来自适配器的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19382197/

相关文章:

Ember.js 绑定(bind)并保存 ownTo 属性

ember.js - 如何使用 ember 辛烷重新加载 ember-data 中的 hasMany 关系?

javascript - ember.js 小部件

javascript - 助手字符串中的 Handlebars 模板标签

jquery - 从 jQuery 对象获取 Ember View

node.js - 使用 Node.js 为 Ember 创建 API

ember.js - Ember : difference between unloadRecord and destroy for new records

javascript - 有人请解释工具链/样板的工作流程,例如 ember-skeletal 或 iridium

javascript - 你能将一个简单的 javascript 数组绑定(bind)到你的 ember.js 模板吗?

javascript - 无法对不在 DOM 中的 Metamorph 执行操作