Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
How to get response body in axios when the status is 400?

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)
  })
}


about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda