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

208
Visualizações
Fetch Api .then functions runs even if response.ok is false

I'm trying to fetch a resource from my local network using the fetch api

After fetching i want to check the response type and act accordingly

But when i receive a status of 500 and i try to return an error callback, the .then() function which was supposed to run only when the response.ok was false runs either way

fetch(testUrl, { headers, method: "POST" })
.then(response => {
if (response.status === 200) { return response.json() }
if (response.status === 401) { Logout() }
if (response.status === 500) {
return setTestApiFetchError({
    'error_type': "SERVER_ERROR",
    "error": true
})
}
})
.then(data => console.log(Data))

the function.then(data => console.log(data)) runs irrespectively

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

0

you need to handle your promise with the resolve and reject arguments

try it like this

const tt =  fetch(testUrl, { headers, method: "POST" })
.then((response,reject)=> {
    const rejectReponse= {
    "error_type": "SERVER_ERROR",
    "error": true
  }
    if (response.ok === true) return response.json() 
        else if (response.status===500) return  reject (rejectReponse)
        })
    
    tt.then(x=>console.log(x)).then(undefined,x=>console.log(x))

to learn more check promises in this article: https://learnjsx.com/category/2/posts/es6-promise

about 4 years ago · Juan Pablo Isaza Relatório

0

Here are a couple links that might help: How can I pass JSON body of Fetch response to Throw Error() with then()? https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch https://usefulangle.com/post/314/javascript-fetch-error-handling

As Ali mentioned, you'd want to reject or throw the 500 response to get it into a catch block. Personally, I'd simply check if response.ok, then handle any errors in the catch:

fetch(testUrl, { headers, method: "POST" })
.then((response,reject)=> {
 if (response.ok) return response.json();
return Promise.reject(rejectReponse)
})
.then(success)
.catch(fail)

Or, if you're able to use async/await:

try{
    const response = await fetch(testUrl, { headers, method: "POST" });
     if (!response.ok) throw response;
     //response is 200-209
    const data = await response.json();
    //etc.
}catch(e){
    if (e.status === 401) logout();
    //handle server/client errors
}
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