Open In App

How to prevent promises swallowing errors ?

Last Updated : 10 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will try to understand how we may prevent the promises swallowing errors using several predefined techniques provided by JavaScript.

Before diving into the major topic of concern let us understand quickly how we may declare a promise using the following syntax.

Syntax:

let promise = new Promise((resolve, reject) => {
    ...
});

Example 1: The following code snippet will help us to understand promise declaration in a much better way:

Javascript




let promise = new Promise((resolve, reject) =>{
    resolve("Hello GeeksforGeeks")
});
 
promise.then(result => console.log(result));


Output:

Hello GeeksforGeeks

Now let us look into our problem statement with which we have to prevent promises swallowing errors. Consider the following code snippet (code example), in which a scenario is illustrated (which is based on real-time working) in which we implemented chaining of .then() method one after the another.

Now if we pass in some parameter that is though not declared anywhere in the code snippet then our promise will catch the error (as a Reference error) and immediately discards (or rejects) the promise and further results in code crashing.

Example 2: See the code snippet below

Javascript




let promise = new Promise((resolve, reject) => {
    resolve();
});
promise
    .then(function () {
        console.log("GeeksforGeeks");
    })
    .then(function () {
        console.log("Hello ", someRandomText);
    });


 
 

Output:

 

 

Now as we may see in the above image’s output, the error is thrown out and thus the promise gets rejected, but we may don’t want that thing to happen, so one of our approaches could be like using one handler function which is chained just after the error which is received from previous .then() method. 

 

Example 3: See the code snippet below

 

Javascript




let promise = new Promise((resolve, reject) => {
    resolve();
})
 
promise
    .then(function () {
        console.log("GeeksforGeeks");
    })
    .then(function () {
        console.log("Hello ", someRandomText);
    }, function (error) {
        console.log("Promise rejected, error message : ", error);
    });


Output:

As we may see this approach (of implementing one handler function) doesn’t seem to give us the correct result, therefore we may have to use the .catch() method after we have received the error.

Example 4: See the code snippet below

Javascript




let promise = new Promise((resolve, reject) => {
    resolve();
})
 
promise
    .then(() => {
        console.log("GeeksforGeeks");
    })
    .then(() => {
        console.log("Hello", someRandomText);
    })
    .catch((error) => {
        console.log("Promise rejected,
            error message : ", error);
    });


Output:

This approach works fine and doesn’t reject the promise which we had declared for execution, instead, it actually fulfills the promise as its state and successfully printouts the error message without crashing the code.

Note: We may have seen successful prevention of promises from swallowing errors (in the above code snippet), but it’s not possible for us every time to chain .catch() with every .then() method having an error. Therefore while working on a project we first have to install the Bluebird, one of the most popular Promise libraries which has an inbuilt method (named onRejection handler) and also one another by default handler(called unhandledRejection) which help us to handle the unhandled rejection over the complete code snippet and this code snippet we have to implement it at once and after implementing it at once we need not worry about the unhandled exceptions at all.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads