1
votes

I've built some login system using NodeJS and Express. My error handling is based on sending the appropriate http status code, along side a custom error message. For instance, an incorrect login would return that:

res.status(401).send({ error: 'Incorrect login' })

As you can see, i'm both setting a status that will cause the promise to fail(at least with Axios), and sending my own error.

On the front end, this is what i have:

 try {
  var response =  await axios({
    method: 'post',
    url: 'http://localhost:3000/signin',
    data: {
      email: this.state.email,
      password: this.state.password
    },
    headers

  })
} catch (error) {
  console.log(response)
  return alert(error)
}

Being that 401 causes the promise to be rejected, i'm left with this built-in error: Request failed with status code 401.

Is there any way to still access the response object? My idea was to handle all error messages from the server, taking this job away from the front.

1
console log the error object?mehulmpt
The error object doesn't contain the responsei.brod

1 Answers

3
votes

Use error.response to get the response from server. For revealing the whole error object, do a console.dir(error)

try {
  var { data } = await axios({
    method: 'post',
    url: 'http://localhost:3000/signin',
    data: {
      email: this.state.email,
      password: this.state.password
    },
    headers

  })
} catch (error) {
  console.dir(error) // error.response contains your response
}