在保存模型可能时,正在处理ember-data中的定制服务器端错误 [英] is handling custom server side errors in ember-data when saving model possible

查看:113
本文介绍了在保存模型可能时,正在处理ember-data中的定制服务器端错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

保存模型时是否有正确的方法来处理自定义错误?举个例子,我说我有一个只有两个属性name和value的模型。当我做:

Is there proper way to handle custom error when saving a model? To give an example, lets say I have a model with just two properties "name" and "value". And when I do :

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调用,以检查名称是否唯一,然后做保存。我只是想知道这里最好/优雅的方法是什么。

One way to work around this is to make extra ajax call to check if the name is unique and then do the save. I am just wondering what is the best/elegant approach here.

谢谢,
Dee

Thanks, Dee

编辑:我认为这可能有助于在服务器端给出更多的上下文。所以这里是:

EDIT : I thought it might help a bit to give more context on the server side of the things in groovy. So here it is:

在我的控制器我有:

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 http://stackoverflow.com/questions/7996569/can-we-create-custom-http-status-codes
        render(status: 422, contentType: 'JSON', text: (errors as JSON))
    }

}

然后在我的余烬控制器中:

Then in my ember controller:

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


推荐答案

deleteRecord 将删除记录。

myModel.save().then(function(response) {
  //if success
  //server responded with {"myModel:{"id":1,"name":"someName","value":"someValue"}"}
},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();
  }

});

这篇关于在保存模型可能时,正在处理ember-data中的定制服务器端错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆