What is the best way to handle 403 errors from ember-data?
I want to know the best way to handle non validation errors, for example I have a bit of code that might return an http 403 if the user is not allowed to perform the action. For example, I have the following code:
contact.set 'something', 'something'
transaction = #get('store').transaction()
transaction.add(contact)
contact.one 'becameInvalid', (result) =>
#display some error message
contact.one 'becameError', (result) =>
# code does not get here for some reason
transaction.rollback()
#display some error message
transaction.commit()
If a 403 error happens then the above becameError handler does not get invoked and the object's state machine is left in the rootState.error state and any subsequent attempts to set a property on the object will fail because of the now infamous and dreaded:
uncaught Error: Attempted to handle event `willSetProperty` on <Radium.Contact:ember2286:17> while in state rootState.error. Called with {reference: [object Object], store: <Radium.Store:ember3219>, name: name}
My thinking is that I can override the didError method:
didError: function(store, type, record, xhr) {
if (xhr.status === 422) {
var json = JSON.parse(xhr.responseText),
serializer = get(this, 'serializer'),
errors = serializer.extractValidationErrors(type, json);
store.recordWasInvalid(record, errors);
} else {
this._super.apply(this, arguments);
}
},
My question is how do I get an object back into a usable state after the state machine has transitioned to rootState.error.
Related
What I want: an error handling that handles different http errors (401, 404, 500) globally. It shouldn't matter where or when an http error occurs.
So far I implemented an error action in the application route that will be called on any adapter errors on route's model hook. That's working fine.
What is not covered is the case when I work with records in other contexts like record.save(). There I need to separately handle the error on the promise.
Moreover I don't only want to have a default error handler but more like a fallback.
Ok, before talking too much let's have an example implementation of my use cases.
application route
The application error action should be the default / fallback error handler.
actions: {
error: function(error) {
var couldHandleError = false;
if (error.errors) {
switch (error.errors[0].status) {
case '401':
// User couldn't get authenticated.
// Redirect handling to login.
couldHandleError = true;
break;
case '404':
case '500':
// Something went unexpectedly wrong.
// Let's show the user a message
couldHandleError = true;
break;
}
}
// return true if none of the status code was matching
return !couldHandleError;
}
}
Some route
In this case the application error action is called.
model: function() {
return this.store.findAll('post');
}
Some controller
In this case the application error action is NOT called.
(I know, the following code probably doesn't make sense, but it is just supposed to illustrate my requirements)
this.store.findRecord('post', 123);
Some other controller
In this example the application error action is not called, for sure, since I use my own handler here (catch()).
But as you can see in the comments I do want to use the default handler for all status codes other than 404.
this.store.findRecord('post', 123).catch(function(reason) {
if (reason.errors[0].status === '404') {
// Do some specific error handling for 404
} else {
// At this point I want to call the default error handler
}
});
So is there a clean and approved way of achieving that? I hope I could make my problem clear to you.
I think I have my final solution I want to share with you. Basically I took the ideas of the guys commenting my question and extended them so they fit my needs.
First I created a mixin with the main logic. Since I want it to be as generic as possible, it distinguishes between a) controller / route and b) jquery / adapter error. So it doesn't matter from where you call it and whether your error object is originally from an jquery Ajax request or an ember adapter.
import Ember from 'ember';
export default Ember.Mixin.create({
ajaxError: function(error) {
if (!error) {
Ember.Logger.warn('No (valid) error object provided! ajaxError function must be called with the error object as its argument.');
return;
}
// Depending whether the mixin is used in controller or route
// we need to use different methods.
var transitionFunc = this.transitionToRoute || this.transitionTo,
couldHandleError = false;
switch (this._getStatusCode(error)) {
case 401:
transitionFunc.call(this, 'auth.logout');
couldHandleError = true;
break;
case 404:
case 500:
// Here we trigger a service to show an server error message.
// This is just an example and currently not the final implementation.
// this.get('notificationService').show();
couldHandleError = true;
break;
}
// For all other errors just log them.
if (!couldHandleError) {
Ember.Logger.error(error);
}
},
_getStatusCode: function(error) {
// First check for jQuery error object
var status = error.status;
// Check for ember adapter error object if it's not a jquery error
if (!status && error.errors && error.errors[0].status) {
status = parseInt(error.errors[0].status);
}
return status;
},
});
Next I reopened some Classes (inside app.js) to make this functionality globally available:
import AjaxErrorMixin from 'app/mixins/ajax-error';
Ember.Route.reopen(AjaxErrorMixin);
Ember.Controller.reopen(AjaxErrorMixin);
Ember.Component.reopen({
_actions: {
// Passing ajaxError per default
ajaxError: function(error) {
this.sendAction('ajaxError', error);
}
}
});
Finally I added some actions to the application route:
actions: {
error: function(error) {
this.send('ajaxError', error);
},
ajaxError: function(error) {
this.ajaxError(error);
},
}
Why do I have two actions doing the same stuff? Well, the error action is called on errors on route's model hook. I could stay with that action, but in the rest of the application where I explicitly call this action I want a more meaningful name. Therefore I also created a ajaxError action. You could stay with one action, for sure.
Now you can use this everywhere:
Route / Controller:
this.ajaxError(error);
Component:
this.sendAction('ajaxError', error);
For sure, you also need to pass the action out of the component to be handled by the application route:
{{some-component ajaxError="ajaxError"}}
This works for nested components, too. You don't need to explicitly send this action further inside the component.js file since we reopened the Component and passt this action into.
I hope I can help other people with that implementation. Also any feedback is welcome.
You can try to do something with these events (put these lines in app.js before app initialization):
Ember.onerror = function (error) {
console.log('Ember.onerror handler', error.message);
};
Ember.RSVP.on('error', function (error) {
console.log('Ember.RSVP error handler', error);
});
Ember.Logger.error = function (message, cause, stack) {
console.log('Ember.Logger.error handler', message, cause, stack);
};
I learned about them from https://raygun.io/blog/2015/01/javascript-error-handling-ember-js/, you may find some details there.
I've got an ember-cli app that's using Ember Data and I'm trying to write an acceptance test that covers the failure case of submitting a form to ask a question. In the test, I'm mocking the response with Pretender to return an errors object, and then asserting that the user is shown a message that lets them know that their submission failed.
The actual assertion that I've written, which checks for an error message to be displayed, is passing. The issue is that I'm also receiving a failure for Error: The backend rejected the commit because it was invalid: {title: can't be blank, body: can't be blank}.
Is there a way to silence this error during tests? Am I approaching this incorrectly? It's not actually an error in this case. The backend should reject the commit, because that's what I'm trying to cover.
Here's the test:
test('errors are displayed when asking question fails', function() {
server.post('/api/v1/questions', function(request) {
var errors = {
title: ["can't be blank"],
body: ["can't be blank"],
};
return jsonResponse(422, { errors: errors });
});
authenticateSession();
visit('/questions/new');
click('button:contains("Ask")');
andThen(function() {
ok(hasContent('There were some errors with your question.'),
'Error message displayed');
});
});
And the relevant action that's being triggered:
save: function(model) {
var _this = this;
model.save().then(function() {
_this.transitionTo('questions.show', model);
}, function() {
_this.wuphf.danger('There were some errors with your question.');
});
},
And the failure that's popping up:
I use the RESTadpater to persist data. When a validation error occurs, I want to return a 422 response and then log the errors and show an indication next to each incorrect field.
My REST response status code is as follows:
Status Code:422 Unprocessable Entity
My REST response body is as follows:
{
"message": "Validation failed",
"errors": [
{
"name": "duplicate"
}
]
}
In my controller, the becameInvalid fires correctly.
App.AuthorsNewController = Ember.ObjectController.extend({
startEditing: function () {
//Create a new record on a local transaction
this.transaction = this.get('store').transaction();
this.set('model', this.transaction.createRecord(App.Author, {}));
},
save: function (author) {
//Local commit - author record goes in Flight state
author.get('transaction').commit();
//If response is success: didCreate fires
//Transition to edit of the new record
author.one('didCreate', this, function () {
this.transitionToRoute('author.edit', author);
});
//If response is 422 (validation problem at server side): becameError fires
author.one('becameInvalid', this, function () {
console.log "Validation problem"
});
}
...
2 QUESTIONS:
I want to log below the 'console.log "Validation problem"', the complete list of errors returned by the server. How can I do that ?
In my hbs template, I want to indicate an error next to the relevant field. How can I do this ?
I am not sure that the data returned via REST adapter is correct. So problem might be at the REST side or at the Ember side ...
Solution:
In controller save function:
author.one('becameInvalid', this, function () {
console.log "Validation problem"
this.set('errors', this.get('content.errors'));
});
In hbs template:
{{view Ember.TextField valueBinding='name'}}
{{#if errors.name}}{{errors.name}}{{/if}}
Here is how I do it, may not be the best practice but it works for me:
instead of using commit(), I use save(), and if you wonder what's the difference, here is the link. I haven't tried your approach of using transaction, but basically I create the record using record = App.Model.createRecord(...), and here is the code of my apiAddShop function inside the AddShopController:
apiAddShop: function() {
//console.log("add shop");
newShop = App.Shop.createRecord({name:this.get('name'), currentUserRole:"owner"});
//this.get('store').commit(); // Use record.save() instead, then() is not defined for commit()
var self = this;
newShop.save().then(function(response){
self.transitionToRoute('shops');
}, function(response){
// if there is error:
// server should respond with JSON that has a root "errors"
// and with status code: 422
// otherwise the response could not be parsed.
var errors = response.errors;
for(var attr in errors){
if (self.hasOwnProperty(attr)) {
self.set(attr+"Error", true);
self.set(attr+"Message", Ember.String.classify(attr)+" "+errors[attr]);
}
console.log(attr + ': ' + errors[attr]);
}
console.log(response.errors.name[0]);
});
},
the above code assume there is a attrError(boolean) and attrMessage(string) for each of the attributes in your form. Then in your template, you could bind the class of your field to these error attributes, such as <div {{bindAttr class=":control-group nameError:error:"}}>, and the error message could be easily display next to the form field such as: <span {{bindAttr class=":help-inline nameError::hidden"}} id="new_shop_error">{{nameMessage}}</span> Here is my example handlebar gist (have to use gist here, since SO is escaping my html inputs).
I've seen this question.
Until nothing is done for ember-data failures handling what can i write to patch it, so that i can have a message if my request doesn't have a 200OK response?
I'm looking at ember-data source code, for example, here's the createRecord function
createRecord: function(store, type, record) {
var root = this.rootForType(type);
var adapter = this;
var data = {};
data[root] = this.serialize(record, { includeId: true });
return this.ajax(this.buildURL(root), "POST", {
data: data
}).then(function(json){
Ember.run(adapter, 'didCreateRecord', store, type, record, json);
}, function(xhr) {
adapter.didError(store, type, record, xhr);
throw xhr;
});
}
I expected something like:
success: //do something
error: //do something else
But there's nothing like this. It's only a then after the ajax request.
What should I do? rewrite completely all the methods i need?
As of this commit ember data now uses promises (specifically the rsvp implementation), which replaces the success: and error: callbacks for a .then() style:
promise.then(function(value) {
// success
}, function(value) {
// failure
});
This is very similar to the previous callback style, but follows the promises style.
The first function is called on success and the second function is called on a failure. Looking at the code you posted shows that didError() is called on ajax failure, which is implemented in the adapter.
didError() (source) calls store.recordWasInvalid() if the status was 422, otherwise it calls store.recordWasError() (source).
store.recordWasInvalid() and store.recordWasError() transition the record into the isError or isValid = false state and triggers the becameError() and becameInvalid() events on the record. You can check these states or subscribe to these events to show your error message.
ember-data.js: https://github.com/emberjs/data/tree/0396411e39df96c8506de3182c81414c1d0eb981
In short, when there is an error, I want to display error messages in the view, and then the user can 1) cancel, which will rollback the transaction 2) correct the input errors and successfully commit the transaction, passing the validations on the server.
Below is a code snippet from the source. It doesn't include an error callback.
updateRecord: function(store, type, record) {
var id = get(record, 'id');
var root = this.rootForType(type);
var data = {};
data[root] = this.toJSON(record);
this.ajax(this.buildURL(root, id), "PUT", {
data: data,
context: this,
success: function(json) {
this.didUpdateRecord(store, type, record, json);
}
});
},
Overall, what is the flow of receiving an error from the server and updating the view? It seems that an error callback should put the model in an isError state, and then the view can display the appropriate messages. Also, the transaction should stay dirty. That way, the transaction can use rollback.
It seems that using store.recordWasInvalid is going in the right direction, though.
This weekend I was trying to figure the same thing out. Going off what Luke said, I took a closer look at the ember-data source for the latest commit (Dec 11).
TLDR; to handle ember-data update/create errors, simply define becameError() and becameInvalid(errors) on your DS.Model instance. The cascade triggered by the RESTadapter's AJAX error callback will eventually call these functions you define.
Example:
App.Post = DS.Model.extend
title: DS.attr "string"
body: DS.attr "string"
becameError: ->
# handle error case here
alert 'there was an error!'
becameInvalid: (errors) ->
# record was invalid
alert "Record was invalid because: #{errors}"
Here's the full walk through the source:
In the REST adapter, the AJAX callback error function is given here:
this.ajax(this.buildURL(root, id), "PUT", {
data: data,
context: this,
success: function(json) {
Ember.run(this, function(){
this.didUpdateRecord(store, type, record, json);
});
},
error: function(xhr) {
this.didError(store, type, record, xhr);
}
});
didError is defined here and it in turn calls the store's recordWasInvalid or recordWasError depending on the response:
didError: function(store, type, record, xhr) {
if (xhr.status === 422) {
var data = JSON.parse(xhr.responseText);
store.recordWasInvalid(record, data['errors']);
} else {
store.recordWasError(record);
}
},
In turn, store.recordWasInvalid and store.recordWasError (defined here) call the record (a DS.Model)'s handlers. In the invalid case, it passes along error messages from the adapter as an argument.
recordWasInvalid: function(record, errors) {
record.adapterDidInvalidate(errors);
},
recordWasError: function(record) {
record.adapterDidError();
},
DS.Model.adapterDidInvalidate and adapterDidError (defined here) simply send('becameInvalid', errors) or send('becameError') which finally leads us to the handlers here:
didLoad: Ember.K,
didUpdate: Ember.K,
didCreate: Ember.K,
didDelete: Ember.K,
becameInvalid: Ember.K,
becameError: Ember.K,
(Ember.K is just a dummy function for returning this. See here)
So, the conclusion is, you simply need to define functions for becameInvalid and becameError on your model to handle these cases.
Hope this helps someone else; the docs certainly don't reflect this right now.
DS.RESTAdapter just got a bit more error handling in this commit but we are still not yet at a point where we have a great recommendation for error handling.
If you are ambitious/crazy enough to put apps in production today with ember-data (as I have been!), it is best to make sure that the likelihood of failures in your API is extremely low. i.e. validate your data client-side.
Hopefully, we can update this question with a much better answer in the coming months.
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.<attribute> in case of input validations, I will be using same trade-off in server validations as well)
<p>{{t 'translations.myString'}}<br>
{{view Ember.TextField valueBinding="attributeName"}}
{{#if model.errors.attributeName.length}}<small class="error">{{model.errors.attributeName}}</small>{{/if}}
</p
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!
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');
}