Javascript. Promises, todo lo que necesitas saber (III)

Cómo gestionar los errores durante la ejecución de Promises

El método catch

const promise = new Promise((resolve, reject) => { ... });
const promise = new Promise(function(resolve, reject) {
setTimeout(() => reject('an error occurred'), 1000);
});
promise.catch(error => console.log(error)); // 'an error occurred'
fetch('https://wrongodmain.com')
.then(response => response.text())
.catch(error => console.log(error.message)); // 'Failed to fetch'
fetch('https://api.com/me')
.then(response => response.json())
.then(user => fetch(`https://api.com/users/${user.id}/articles`))
.then(response => response.json())
.catch(error => console.log(error.message));

Gestión de errores

fetch('https://wrongodmain.com')
.then(response => response.text())
.catch(error => { throw error; })
.catch(() => console.log('called'));
fetch('https://wrongodmain.com')
.then(response => response.json())
.catch(error => { return { id: 1, fullname: 'default user'};})
.then(user => console.log(user.fullname)); // default user

Reject sin catch

const promise = new Promise(function(resolve, reject) {
reject('an error occurred');
});
// Uncaught (in promise) an error occurred
const promise = new Promise(function(resolve, reject) {
reject('an error occurred');
});
window.addEventListener('unhandledrejection', function(event) {
console.log(event.promise);
console.log(event.reason);
});

Excepciones

const promise = new Promise((resolve, reject) => {
throw new Error('An error occurred');
})
promise.catch(console.log); // An error occurred
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(function() { throw new Error('An error occurred');})
.catch(error => console.log(error.message)); //'An error occurred'
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(function() { console.log(foo.bar); })
.catch(error => console.log(error.message)); // foo is not defined

Catch y setTimeout

new Promise(function(resolve, reject){
setTimeout(() => {
throw new Error('error')
}, 1000)
}).catch(error => console.log('not called!'));
// Prints in console: 'Uncaught Error: error'
new Promise(function(resolve, reject) {
setTimeout(() => reject('error'), 1000)
}).catch(error => console.log('called!'));

Conclusiones

¿Quieres recibir más artículos como este?

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store