Search code examples
ember.jsember-dataember-cli

Server side errors not populated in Ember model with RESTAdapter


While trying to handle server side errors in Ember application, I am unable to show the errors in templates as the model is not populated with the received errors.

Versions used:
Ember-cli: 2.4.3
Ember-data: 2.4.2
adapter: RESTAdapter

The template file contains the form for user sign-up as shown:

    {{input type="text" value=username }}  
    {{#each model.errors.username as |error|}}  
         {{error.message}}  
    {{/each}}  
    {{input type="text" value=email }}  
    <button {{action 'register'}}>Register</button>  

The routes file contains the action 'register' to save the user:

register: function(){  
    var username = this.controller.get('username');  
    var email = this.controller.get('email');  
    var user = this.store.createRecord('user',{  
            email: email,  
            username: username  
        });  
    user.save().then(function(){  
        //handle success  
     },function(error){  
       //handle error  
     });  
 }); 

The model looks like:

export default Model.extend({  
    email: attr(),  
    username: attr()  
}); 

The API I am using responds with a status 422 and error as shown:

{    
   "errors":[  
      {  
         "detail":"can't be blank",
         "source":{  
            "pointer": "/data/attributes/username"
         }
      }
   ]
}  

According to the docs of DS.Errors Errors can be displayed by accessing their property name to get an array of all the error objects for that property. And that is what I am trying to do in my template file.
Also I tried accessing the messages property on the error object without success.

{{#each model.errors.messages as |message|}}
    {{message}}
{{/each}}

When I try to log in console the length property on errors i.e

 user.save().then(function(){  
        //handle success  
     },function(error){  
       //handle error  
       console.log(user.get('errors.length'));
     }); 

It always gives me 0. However

console.log(user.get('errors.username.length'));  

gives the desired output, but still the errors are not visible in the template.
Tried overriding ajaxError in RESTAdapter as mentioned in this post 24027053 but no luck.
I don't know what I am doing wrong. Please Help!


Solution

  • I think the error lies within:

    user.save().then(function(){  
        //handle success  
     },function(error){  
       //handle error  
       console.log(user.get('errors.length'));
     }); 
    

    The user is not saved, therefore it has no error. Try this:

     user.save().then(function(){  
        //handle success  
     },function(error){  
       //handle error --> how do you handle it? Are you maybe overriding the default behaviour?
       // you might want to put a 'debugger;' statement here in order to see, what the response actually looks like  
       console.log(error.errors);
     });