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

前端 未结 4 1298
后悔当初
后悔当初 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:42

    Since there's currently no good solution in stock Ember-Data, I made my own solution by adding an apiErrors property to DS.Model and then in my RestAdapter subclass (I already needed my own) I added error callbacks to the Ajax calls for createRecord and updateRecord that save the errors and put the model in the "invalid" state, which is supposed to mean client-side or server-side validations failed.

    Here's the code snippets:

    This can go in application.js or some other top-level file:

    DS.Model.reopen({
      // Added for better error handling on create/update
      apiErrors: null
    });
    

    This goes in the error callbacks for createRecord and updateRecord in a RestAdapter subclass:

    error: function(xhr, textStatus, err) {
        console.log(xhr.responseText);
        errors = null;
        try {
            errors = JSON.parse(xhr.responseText).errors;
        } catch(e){} //ignore parse error
        if(errors) {
            record.set('apiErrors',errors);
        }
        record.send('becameInvalid');
    }
    

提交回复
热议问题