Ember data Rest adapter error handling not working

陌路散爱 提交于 2019-12-11 11:57:08

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/31712857/ember-data-rest-adapter-error-handling-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!