How should errors be handled when using the Ember.js Data RESTAdapter?

前端 未结 4 1295
后悔当初
后悔当初 2020-12-12 14:13

ember-data.js: https://github.com/emberjs/data/tree/0396411e39df96c8506de3182c81414c1d0eb981

In short, when there is an error, I want to display error messages in th

4条回答
  •  旧巷少年郎
    2020-12-12 14:36

    I just ran into such a situation, not sure if this is already explained anywhere.

    I am using:

    Em.VERSION : 1.0.0
    DS.VERSION : "1.0.0-beta.6"
    Ember Validations (dockyard) : Version: 1.0.0.beta.1
    Ember I18n
    

    The model was initially mixedin with Validation mixin.

    App.Order = DS.Model.extend(Ember.Validations.Mixin, {
    .....
    someAttribute : DS.attr('string'),
    /* Client side input validation with ember-validations */
    validations : {
        someAttribute : {
            presence : {
                message : Ember.I18n.t('translations.someAttributeInputError')
            }
        }
    }
    });
    

    In the template, corresponding handlebars is added. (note that ember validations will automatically add errors to model.errors. in case of input validations, I will be using same trade-off in server validations as well)

    {{t 'translations.myString'}}
    {{view Ember.TextField valueBinding="attributeName"}} {{#if model.errors.attributeName.length}}{{model.errors.attributeName}}{{/if}}

    Now, we will be saving the Order

    App.get('order').save().then(function () {
      //move to next state?
    }, function(xhr){
      var errors = xhr.responseJSON.errors;
      for(var error in errors){ //this loop is for I18n
        errors[error] = Ember.I18n.t(errors[error]);
      }
      controller.get('model').set('errors', errors); //this will overwrite current errors if any
    });
    

    Now if there is some validation error thrown from server, the returned packet being used is

    {"errors":{"attributeName1":"translations.attributeNameEror",
     "another":"translations.anotherError"}}
    
    status : 422
    

    It is important to use status 422

    So this way, your attribute(s) can be validated client side and again on server side.

    Disclaimer : I am not sure if this is the best way!

提交回复
热议问题