DEV Community

Discussion on: JavaScript: Error handling with Promises and Async/Await

Collapse
 
dbigpot profile image
dbigpot • Edited

@fluffystark pretty much answers your question. However, I'll explain it further just in case -

Say you have a promise function called somePromise. When you do a throw new Error() inside your .then() block, like below

try {
    somePromise()
        .then((data) => {
            throw new Error('Inner error');
        })
        .catch((promiseError) => {
            console.log(promiseError); // Prints Inner error
        });
} catch (error) {
    // Handle all module errors here
}

the error will get passed to the .catch() block of somePromise() and not the catch block of the try-catch.

When having multiple promise statements in your code, it can become cumbersome to handle each promise's errors in its own .catch() block. Using async/await allows you to handle all errors in one place. I hope this cleared your doubt. :)