Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

198
Views
Las funciones Fetch Api .then se ejecutan incluso si response.ok es falso

Estoy tratando de obtener un recurso de mi red local usando la API de obtención

Después de buscar, quiero verificar el tipo de respuesta y actuar en consecuencia

Pero cuando recibo un estado de 500 y trato de devolver una devolución de llamada de error, la función .then() que se suponía que se ejecutaría solo cuando la response.ok era false se ejecuta de cualquier manera

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

la función .then(data => console.log(data)) se ejecuta independientemente

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

necesita manejar su promesa con los argumentos de resolución y rechazo

inténtalo así

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

para obtener más información, consulte las promesas en este artículo: https://learnjsx.com/category/2/posts/es6-promise

about 4 years ago · Juan Pablo Isaza Report

0

Aquí hay un par de enlaces que pueden ayudar: ¿Cómo puedo pasar el cuerpo JSON de la respuesta Fetch a Throw Error() con then()? https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch https://usefulangle.com/post/314/javascript-fetch-error-handling

Como mencionó Ali, querrás rechazar o lanzar la respuesta 500 para colocarla en un bloque catch. Personalmente, simplemente verificaría si response.ok, luego manejaría cualquier error en la captura:

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

O, si puede usar 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!