mercredi 30 septembre 2015

Backend Validation with RESTAdapter always "The adapter rejected the commit because it was invalid"

Configuration

  • Backend = Laravel 5.1, with Dingo API
  • Frontend = Ember 1.13.6, Ember Data 1.13.7
  • Adapter = Ember Data RESTAdapter

The Problem

I'm trying to handle backend validation errors on my first Ember application. When errors are returned from the server, I get this error:

Error: The adapter rejected the commit because it was invalid
at new Error (native)
at Error.EmberError (http://localhost:4200/assets/vendor.js:26266:21)
at Error.ember$data$lib$adapters$errors$$AdapterError (http://localhost:4200/assets/vendor.js:69564:50)
at Error.ember$data$lib$adapters$errors$$InvalidError (http://localhost:4200/assets/vendor.js:69637:52)
at ajaxError (http://localhost:4200/assets/frontend.js:16:24)
at ember$data$lib$system$adapter$$default.extend.ajax.Ember.RSVP.Promise.hash.error (http://localhost:4200/assets/vendor.js:71327:31)
at jQuery.Callbacks.fire (http://localhost:4200/assets/vendor.js:3350:30)
at Object.jQuery.Callbacks.self.fireWith [as rejectWith] (http://localhost:4200/assets/vendor.js:3462:7)
at done (http://localhost:4200/assets/vendor.js:9518:14)
at XMLHttpRequest.jQuery.ajaxTransport.options.send.callback (http://localhost:4200/assets/vendor.js:9920:8)

The response from the backend has a 422 Unprocessable Entity header, and the content is:

{
     "message":"Couldn't save client",
     "errors":{
          "name":["The name field is required."],
          "email":["The email field is required."]
      },
     "status_code":422
}

Tried (and Failed) Solutions

  • Ember data Rest adapter error handling not working
    Extending the RESTAdapter to override the ajaxError function, mine currently looks like this:

    ajaxError: function(jqXHR) {
    var error = this._super(jqXHR);
    if (jqXHR && jqXHR.status === 422) {
        var jsonErrors = Ember.$.parseJSON(jqXHR.responseText).errors;
        return new DS.InvalidError(jsonErrors);
    } else {
        return error;
    }
    }
    
    
  • Adding a catch statement to the save method, my save action is currently:

     save() {
        var self = this;
    
        function transitionToPost(post) {
            self.transitionToRoute('clients.show', post);
        }
    
        function failure(reason) {
            // handle the error
            console.log(reason);
            return false;
        }
    
        this.get('model').save().then(transitionToPost, failure).catch(failure);
    }
    
    
  • Testing out the ActiveModelAdapter - not sure what I was expecting to acheive with this one, but I got desperate; the result was still the same.

  • Ember Docs (http://ift.tt/1Vrk4oN)
    As you can see in my controller code above, I actually used this as a base

Please can you have a look and advise? Thanks in advance for any help!




Aucun commentaire:

Enregistrer un commentaire