JS-Data addAction method throws instead of rejecting the promise with the error message

205 views Asked by At

In the js-data library, I have added a custom query with the addAction() method as shown here. Now when my server returns a 4xx error code upon calling that custom action, an error is thrown but the server response (which is send) is nowhere to be found:

store.getMapper('school').getTeacherReports(1234, {
  basePath: 'reports'
}).then(function(response) {
  console.log('response', response.data)
}).catch(function(err) {
  console.log('err', err);
})

How should I handle this? Is there some method I don't know of that I should use? I already tried the response and responseError properties in the addAction() according to the docs.

2

There are 2 answers

1
Baboo On

The then function can take two parameters:

then(
  onSuccess: Function,
  onRejection: Function
)

So here is how you can handle the rejection due to the 4xx error:

store.getMapper('school').getTeacherReports(1234, {
  basePath: 'reports'
}).then(
  function (response) { // on success
    console.log('response', response.data);
  },
  function (error) { // on error
    console.error(error);
  },
)
0
Raymundus On

This has to do with axios: The rejected error object indeed has the response as a property (source code) but it doesn't appear as such in console outputs because error objects are shown differently in the console. The following shows the underlying properties:

store.getMapper('school').getTeacherReports(1234, {
  basePath: 'reports'
}).then(function(response) {
  console.log('response', response.data)
}).catch(function(err) {
  let errorObject = JSON.parse(JSON.stringify(error))
  console.log(errorObject)
});