如何使用ember.js处理http请求失败?

时间:2013-05-08 12:51:30

标签: ember.js ember-data

我见过this question

直到没有为ember-data失败做任何事情处理我可以写什么来修补它,所以如果我的请求没有200OK响应,我可以收到消息?

我正在查看ember-data源代码,例如,这里是createRecord函数

createRecord: function(store, type, record) {
    var root = this.rootForType(type);
    var adapter = this;
    var data = {};

    data[root] = this.serialize(record, { includeId: true });

    return this.ajax(this.buildURL(root), "POST", {
      data: data
    }).then(function(json){
      Ember.run(adapter, 'didCreateRecord', store, type, record, json);
    }, function(xhr) {
      adapter.didError(store, type, record, xhr);
      throw xhr;
    });
  }

我期待的是:

success: //do something
error: //do something else

但是没有这样的。在ajax请求之后,它只是then

我该怎么办?完全重写我需要的所有方法?

1 个答案:

答案 0 :(得分:4)

this commit开始,ember数据现在使用promises(特别是rsvp implementation),它替换了success:样式的error:.then()回调:< / p>

promise.then(function(value) {
  // success
}, function(value) {
  // failure
});

这与之前的回调样式非常相似,但遵循承诺样式。

第一个函数在成功时调用,第二个函数在失败时调用。查看您发布的代码,显示在ajax失败时调用didError(),这是在适配器中实现的。

didError()source)如果状态为422则调用store.recordWasInvalid(),否则调用store.recordWasError()source)。

store.recordWasInvalid()store.recordWasError()将记录转换为isErrorisValid = false状态,并触发记录中的becameError()becameInvalid()事件。您可以检查这些状态或订阅这些事件以显示您的错误消息。