Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda