@R_306_301@时是否有正确的方法来处理自定义错误?举个例子,假设我的模型只有两个属性“name”和“value”.当我这样做时:
var myModel = this.get('store').createRecord('myModel',{"name": "someName","value": "someValue"}); myModel.save().then(function() { //if success //server responded with {"myModel:{"id":1,"name":"someName","value":"someValue"}"} },function() { //if failure //server responded with {"error":"some custom error message"} //BUT HOW TO CATCH THIS AND POSSIBLY REMOVE THE MODEL FROM THE STORE });
解决此问题的一种方法是进行额外的ajax调用以检查名称是否唯一,然后执行保存.我只是想知道这里最好/最优雅的方法是什么.
谢谢,
迪伊
编辑:我认为在groovy中为事物的服务器端提供更多上下文可能会有所帮助.所以这里是:
在我的控制器中我有:
def create() { try { newRow = someService.create(params) render someService.list(newRow) as JSON//returns data in format needed by ember-data } catch (ValidationException ex) { def errors = ["errors":[]] ex.errors.allErrors.each{ if(it.arguments[0] == "fieldName" && it.code=="constrantViolated"){ errors.errors.push(["field":it.arguments[0],"message":"some custom message"]) } } //I am using 422 here because of post in https://stackoverflow.com/questions/7996569/can-we-create-custom-http-status-codes render(status: 422,contentType: 'JSON',text: (errors as JSON)) } }
然后在我的余烬控制器中:
var myModel = self.get('store').createRecord('myModel ',myModelDataInJSON); myModel .save().then(function () { //if success },function (response) { myModel .deleteRecord(); var errors = $.parseJSON(response.responseText); for (var key in errors.errors) { //do something } });
解决方法@H_403_21@
deleteRecord将删除记录.
myModel.save().then(function(response) {
//if success
//server responded with {"myModel:{"id":1,function(response) {
//if failure
//server responded with {"error":"some custom error message"}
//BUT HOW TO CATCH THIS AND POSSIBLY REMOVE THE MODEL FROM THE STORE
if(response.error=='no good'){
myModel.deleteRecord();
}
});
myModel.save().then(function(response) { //if success //server responded with {"myModel:{"id":1,function(response) { //if failure //server responded with {"error":"some custom error message"} //BUT HOW TO CATCH THIS AND POSSIBLY REMOVE THE MODEL FROM THE STORE if(response.error=='no good'){ myModel.deleteRecord(); } });