Search code examples
javascriptember.jserror-handlingember-data

How to set custom response json in ember-data when dealing with errors


I'm using now:

  • ember: 3.8.1
  • ember-data: 3.10.0

I'm trying to send an error response from Grails API with some additional data. It looks something like this:

respond(
    status: HttpStatus.UNPROCESSABLE_ENTITY, 
    errors: errors
    additionalData: someMap
)

On the frontend side with Ember I'm trying to catch it with:

object.save().then(function () {
    // (...)
}).catch((response) => {
    // Here I want to access "response.additionalData"
    // (...)
});

Now, I know that ember-data has it's own way to handle and bind errors response (https://davidtang.io/2016/01/09/handling-errors-with-ember-data.html) but in ember-data: 2.10.0 I was able to catch and handle errors with additional data in catch with response.additionalData.

In version I'm using response.additionalData is always undefined and I can't get it in any way. It's coming from backend because I can see it in browser dev tools in response.

How can I achieve this in newest ember-data? I did try to write adapter and override handleResponse function but even my own CustomErrorClass still was like native one.

Any help would be appreciated. Thanks in advance!


Solution

  • So, I did try few options with meta member of JSONAPI format as described here:

    At first, that didn't help, the answer from the server was:

    Error: Assertion Failed: Your transport record was saved to the server, but the response does not have an id and no id has been set client side. Records must have ids. Please update the server response to provide an id in the response or generate the id on the client side either before saving the record or while normalizing the response.
    

    Then I added response status to the HttpServletResponse response object like so:

    response.status = HttpStatus.UNPROCESSABLE_ENTITY.value()
    

    So the full response part looks like this:

    response.status = HttpStatus.UNPROCESSABLE_ENTITY.value()
    render([errors: [[status: HttpStatus.UNPROCESSABLE_ENTITY,
                      title : e.message,
                      detail: message,
                      meta  : [additionalData: additionalData]]
    ]] as JSON)
    

    Also notice that errors content is in doubles brackets [[ for JSONAPI format to be valid.

    With this, I finally got the right answer with meta member in it:

    enter image description here