Considere el código a continuación que se supone que debe hacer algo cuando la respuesta de un punto final web es "200-ish" (2xx y similar) y algo más cuando la respuesta es 404 (y algo más para no 404, y administrar problemas de red )
fetch('https://httpstat.us/404') .then((r) => { if (r.ok) { console.log(`response 200-ish`) return r // go to the next .then() } else { console.log(`response is not 200-ish`) return Promise.reject(r.status) // the chain for then() breaks here } }) .then((r) => { console.log('do stuff for 200-ish') }) .catch((err) => { if (err === 404) { console.log('do 404 stuff') } else { console.log('do stuff because of another response from the API') } // how to address network problems?? })https://httpstat.us/200 , el código está bienhttps://httpstat.us/404 , el código está bienhttps://httpstat.us/500 (= ni 200 ni 404, pero una respuesta correcta del servidor API), el código está bien por casualidadhttps://httpstat.usXXXXXXXX/500 (= una URL incorrecta que genera un error de red), el código no está bien En otras palabras, el último else captura cualquier cosa que no se haya verificado explícitamente.
¿Cómo puedo diferenciar entre una ruptura explícita de la cadena de promesas (exponiendo un código de retorno) y errores de red?
Necesitará una cadena de promesas ligeramente compleja:
let fetchPromise = fetch('https://httpstat.us/404'); fetchPromise.catch((e) => { // Do stuff only for network errors }); fetchPromise.then((r) => { if (r.ok) { return r.json().then( /* The JSON here is just a example if you need to wrap more promises */ /* Do something with a 200 */ ) } else { /* Do something with non-200 ish */ } })Alternativamente:
try: let response = await fetch('...'); catch (ex) { /* do something with network errors */ } if (!response.ok) { /* do something with non-network errors */ throw new Error() } /* do something with 200 */