Why does the Axios error object not show the contents in console.log?

Viewed 107

I have an Express API endpoint that responds with an error like such:

async(req,res) { 
try {
  // Does something here
} 
catch(error) {
    const Err = new Error();
    Err.message = "Username or password does not match";
    Err.code = 401;

    return res.status(Err.code).send(Err.message);
}

The calling page makes a call to the above endpoint like such:

try {    
 const response = await axios.get('/user/12345');
console.log('successful!')
} 
catch(error) {
  console.log(error)                // A
  console.log(error.response.data)  // B
}

When the above calling page logs the error it shows up as this:

A

Error: Request failed with status code 401

createError webpack://app/./node_modules/axios/lib/core/createError.js?:17 ....

B

Username or password does not match

My question is that why does A not show the contents of the error response with the data, headers, config etc objects? This was very confusing when I didn't know I had to use error.response.data to get to the error message itself.

1 Answers

I would try something like

async(req,res) { 
try {
  // Does something here
} 
catch(error) {
    const message = "Username or password does not match";
    const code = 401;    
    res.status(code).send(message);
}

and

const response = axios.get('/user/12345')
     .then(res => console.log({res}))
     .catch(err=> console.log({err}))
   
Related