Quantcast
Channel: Ember.JS - Latest topics
Viewing all articles
Browse latest Browse all 4829

Error Handling with Rest Adapter and custom error json

$
0
0

@mtangoo wrote:

I have this Rest adapter

//app/adapters/application.js
import Ember from 'ember';
import DS from 'ember-data'; 

export default DS.RESTAdapter.extend({
    //defaultSerializer: 'JSONSerializer',
    host: 'http://localhost:8081/index.php',
    namespace: 'v1',    
});

I can post to my API fine. The problem is, when I have validation error I cannot receive them in my model. I create a model in response to data sent from component via SendAction() and here is signup route

import Ember from 'ember';

export default Ember.Route.extend({     
    actions:{
        signUp(userInfo){  
            let route = this;
            let user = this.store.createRecord('user', userInfo);
            user.save().then(function(){ //success
                
            }, function(error){ //error  
                alert(error);  // I always get --> Error: The adapter rejected the commit because it was invalid
            });
        }
    }, 
     
});

I always get " Error: The adapter rejected the commit because it was invalid" no matter what I do.

Here is my API error response: [{"field":"first_name","message":"First Name cannot be blank."},{"field":"last_name","message":"Last Name cannot be blank."},{"field":"mobile","message":"Mobile cannot be blank."},{"field":"gender","message":"Gender cannot be blank."},{"field":"username","message":"Username cannot be blank."},{"field":"password","message":"Password cannot be blank."},{"field":"secret_word","message":"Secret Word cannot be blank."},{"field":"created_at","message":"Created At cannot be blank."},{"field":"updated_at","message":"Updated At cannot be blank."}]

I have tried everything I could find in google (SO, Ember forum et al) but with no avail. Here is my latest attempt to get it work.

import Ember from 'ember';
import DS from 'ember-data'; 

export default DS.RESTAdapter.extend({
    //defaultSerializer: 'JSONSerializer',
    host: 'http://localhost:8081/index.php',
    namespace: 'v1',   
  
      parseErrorResponse: function(responseText) {
        let json = responseText;
        let jsonapiError;
        
        try { 
        json = Ember.$.parseJSON(responseText);
        let errors = [];
        for(let i=0; i<json.length; i++)
        {
            let obj = json[i];
            let attrName = obj.field;
            let message = obj.message;
            errors.push({"attribute":attrName, "message":message});
        }
        jsonapiError = {"errors":errors}; 
          
        } catch (e) {}

        return jsonapiError;
      },
     
});

So far I have run out of ideas and would appreciate any pointer or help. TIA, Stefano

Posts: 7

Participants: 2

Read full topic


Viewing all articles
Browse latest Browse all 4829

Trending Articles