Catching error messages from a NodeJS express application using axios

Viewed 726

I have an application using NodeJS in backend and specifically Express framework to serve API routes. My client side is written in ReactJS, making use of axios to make API requests.

First time using axios package, and i can't find how to access error messages from the response.

My API returns as error responses:

res.status(404).send({ error: 'Error Message' });

In axios i have:

axios.post('/api/users', newUser)
  .then((user) => {
    console.log(`User created: ${JSON.stringify(user)}`);
  }).catch((err) => {
    console.log(`Error : ${JSON.stringify(err)}`);
  });

console.log(`Error : ${JSON.stringify(err)}`) prints:

{
  "message": "Request failed with status code 404",
  "name": "Error",
  "stack": "Error: Request failed with status code 404\n    at createError (http://localhost:3000/static/js/0.chunk.js:13853:15)\n    at settle (http://localhost:3000/static/js/0.chunk.js:14074:12)\n    at XMLHttpRequest.handleLoad (http://localhost:3000/static/js/0.chunk.js:13328:7)",
  "config": {
    "url": "/api/users",
    "method": "post",
    "data": "someData",
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "Authorization": "Bearer xxxxx",
      "Content-Type": "application/json;charset=utf-8"
    },
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1
  }
}

I can't find nowhere in that err object the response message from the server, i have even tried:

res.status(404).json({ error: 'Error Message' });

with no success.

2 Answers

Per this comment, try accessing err.response in the catch block.

The err.response would have an object { error: 'Error Message' } so you can access that using err.response.error. also make sure err.response.error exists because if it doesn't and you try to access it will throw an error inside the catch saying err.response.error is undefined

axios.post('/api/users', newUser)
  .then((user) => {
    console.log(`User created: ${JSON.stringify(user)}`);
  }).catch((err) => {
   if(err.response.error)
    console.log(`Error : ${JSON.stringify(err.response.error)}`);
  });
Related