垃圾数据休眠适配器错误处理不起作用 [英] Ember data Rest adapter error handling not working
本文介绍了垃圾数据休眠适配器错误处理不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
task.save()然后(
function(){alert(成功);},
function(){alert(fail);}
).catch(
function(){alert(catch error);}
);
当记录有效时,我收到成功提醒,但是当记录无效时,没有得到失败警报或catch错误。在控制台中,我得到:
POST http:// localhost:8080 / api / tasks 422(Unprocessible Entity)
错误:适配器拒绝了提交,因为它是无效的
api的响应如下所示:
{errors:{name:[不能为空],parent_task:[]我使用的是Ember Data 1.13。
解决方案
您需要扩展适配器来处理错误,REST适配器不会为您(只有活动模型一个)
这样的东西:
App.ApplicationAdapter = DS .RESTAdapter.extend({
ajaxError:function(jqXHR){
var error = this._super(jqXHR);
if(jqXHR&& jqXHR.status = ==
var response = Ember。$。parseJSON(jqXHR.responseText),
errors = {};
if(response.errors!== undefined) {
var jsonErrors = response.errors;
Ember.EnumerableUtils.forEach(Ember.keys(jsonErrors),function(key){
errors [Ember.String.camelize(key)] = jsonErrors [key];
});
}
返回新的DS.InvalidError(errors);
} else {
return error;
}
}
});
I have a basic Ember app and I am trying to handle validation errors on save (model is using the REST Adapter). In my route I am doing:
task.save().then(
function() {alert("success");},
function() {alert("fail");}
).catch(
function() {alert("catch error");}
);
When the record is valid I get the "success" alert, but when record is invalid, I do not get the "fail" alert OR "catch error". In the console I get:
POST http://localhost:8080/api/tasks 422 (Unprocessable Entity)
Error: The adapter rejected the commit because it was invalid
The response from the api look like this:
{"errors":{"name":["can't be blank"],"parent_task":[]}}
I am using Ember Data 1.13.
解决方案
You need to extend your adapter to handle the errors, the REST Adapter does NOT do this for you (only the Active Model one)
Something like this:
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var response = Ember.$.parseJSON(jqXHR.responseText),
errors = {};
if (response.errors !== undefined) {
var jsonErrors = response.errors;
Ember.EnumerableUtils.forEach(Ember.keys(jsonErrors), function(key) {
errors[Ember.String.camelize(key)] = jsonErrors[key];
});
}
return new DS.InvalidError(errors);
} else {
return error;
}
}
});
这篇关于垃圾数据休眠适配器错误处理不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文