How to get response body in axios when the status is 400?

Viewed 1291

I'm developing an application and I want to use the status code 400 when a user sends invalid or incomplete data, but when axios receives a 400 status code it throws an error and I can't get the response from it, it just gives me a error that includes the request but not the response, how am I supposed to handle this?

const getIdTypes = () => {
  return axios_instance.get
    (idTypesUrl)
}


const getValidIdTypes = async () => {
  return infoActions.getIdTypes()
  .then(res => {
    if (res.status !== 200 && res.status !== 201) {
      pushToFlasher(res.data)
    }
    setValidIdTypes(res.data)
  })
  .catch(err => {
    if (err.request) {
      console.log("err:", err.request)
    }
     if (err.response) {
      console.log("err:", err.response)
    }
    // pushToFlasher(err.response.data)
  })
}


2 Answers

You can specify which status codes are valid when you create an instance:

const instance = axios.create({
  baseURL: 'some api url',
  timeout: 1000 * 30,
  validateStatus: (status) => {
    return status >= 200 && status < 500
  },
})

So here all statuses between 200 and 500, will be considered valid and not throw an error.

In your case you can just return status === 400

in catch block, you can access error response that server sends by getting err.response.data object:

const getValidIdTypes = async () => {
  return infoActions.getIdTypes()
  .then(res => {
    if (res.status !== 200 && res.status !== 201) {
      pushToFlasher(res.data)
    }
    setValidIdTypes(res.data)
  })
  .catch(err => {
      console.log(err.response.data)
  })
}

for exmaple if server send this object:

{
    status: 400,
    message: "there is a problem"
}

you can get "message" this way: err.response.data.message

Related