I’m not able to send the API errors in a format that Ember/EmberData (both v3.22.0) and is able to consume for model errors to display them in templates. I’m using RESTAdapter and RESTSerializer.
My product model looks like this:
export default class ProductModel extends Model {
@attr('string') name;
...
}
The expected default format is explained in the Documentation:
What I understand reading this, is:
// api response
{
errors: [
{
'attribute': 'name',
'message': 'This field cannot be blank.'
}
]
}
But I also tried many other formats. To see if the errors get properly processed by Ember, I console.log them in the catch block like this but still empty.
@action async save(product) {
try {
await product.save();
} catch(res) {
console.log('errors', product.get('errors')); // []
}
}
Hope someone could help me with that!
IIRC the best way to handle this sort of situation is overriding extractErrors
in your Ember serializer. Per the docs for that method I think it (RESTSerializer just inherits this method from JSONSerializer) expects the errors array to be in JSON API format (though I do find it curious that JSONSerializer/RESTSerializer don’t do any formatting from other types, maybe there just aren’t enough conventions around that to adopt one).
So i think your options would be either match the JSON:API error format on your backend (example below) or use whatever format is easiest from your API and convert the error format in your serializer with extractErrors
.
{
"errors": [
{
"detail": "This username is already taken!",
"source": {
"pointer": "data/attributes/username"
}
}, {
"detail": "Doesn't look like a valid email.",
"source": {
"pointer": "data/attributes/email"
}
}
]
}
Thank you for your quick reply!
I wanted to avoid custom implementation in favour of basic functionality that should work out of the box, so I kept on trying and found the solution:
First: The Backend was sending status code of 400, but Ember is expecting a 422 (unprocessable unit) in order to create an error of type InvalidError
, so that it will be considered as model errors.
Second: I had to send the errors from the Backend in the format you were also suggesting even though, according to the docs I understood that there should only be these two keys per error (attribute
and message
).
Anyway - Thanks for your help and have a good start into the new year!
1 Like