Error Handling with Promises
Promises/Async/Await: Error / Promises
How is error handling achieved with promises in JavaScript?
View Answer:
Interview Response: When a promise rejects, the control gets sent to the nearest rejection handler. An error may occur while attempting to return a promise. The catch method is the simplest way to handle error handling. The dot catch does not have to be instant, and it might emerge after one or more dot thens.
Code Example:
fetch('https://no-such-server.blabla') // rejects
.then((response) => response.json())
.catch((err) => alert(err)); // TypeError: failed to fetch (the text may vary)
What is an implicit try…catch concerning promises in JavaScript?
View Answer:
Interview Response: The code of a promise executor and promise handlers have an "invisible try..catch" around it. If an exception happens, it gets caught and treated as a rejection. This outcome happens not only in the executor function but also in its handlers. If we throw inside a .then handler, that means a rejected promise, so the control jumps to the nearest error handler. This outcome happens for all errors, not just those caused by the throw statement, including programming errors.
Code Example:
new Promise((resolve, reject) => {
throw new Error('Whoops!');
}).catch(alert); // Error: Whoops!
// Works exactly the same as this:
new Promise((resolve, reject) => {
reject(new Error('Whoops!'));
}).catch(alert); // Error: Whoops!
// Example in dot then
new Promise((resolve, reject) => {
resolve('ok');
})
.then((result) => {
throw new Error('Whoops!'); // rejects the promise
})
.catch(alert); // Error: Whoops!
In a regular try..catch, we can analyze the error and maybe rethrow it if we can't handle it. Is the same thing possible for promises?
View Answer:
Interview Response: Yes, the same thing is possible for promises. If we throw inside .catch, the control goes to the next closest error handler, and if we handle the error and finish usually, it continues to the next closest successful .then handler.
Code Example:
// the execution: catch -> then
new Promise((resolve, reject) => {
throw new Error('Whoops!');
})
.catch(function (error) {
alert('The error is handled, continue normally');
})
.then(() => alert('Next successful handler runs'));
What happens when an error is unhandled in a promise?
View Answer:
Interview Response: In practice, something has gone wrong, just like with regular unhandled code errors. The script terminates with an error message on the console. Unhandled promise rejections behave similarly, and the JavaScript engine monitors such rejections and emits a global error in such cases. We may catch such errors in the browser by utilizing the event `unhandledrejection`.
Code Example:
window.addEventListener('unhandledrejection', function (event) {
// the event object has two special properties:
alert(event.promise); // [object Promise] - the promise that generated the error
alert(event.reason); // Error: Whoops! - the unhandled error object
});
new Promise(function () {
throw new Error('Whoops!');
}); // no catch to handle the error