JavaScript Promise Error Handling

JavaScript Promise Error Handling with Examples

In this article, I am going to discuss JavaScript Promise Error Handling with Examples. Please read our previous article where we discussed JavaScript Promise.race() vs Promise.all() in detail. 

JavaScript Promise Error Handling

Promise chains are good at error handling. When a promise rejects, the control jumps to the closest rejection function. Errors thrown from promises are handled by the second parameter (reject) passed to then() or by the handler passed to catch()

.then(null, error => { /* handle error here */ });
// or
foo().catch(error => { /* handle error here */ });

Synchronously throwing an error from function that should return a promise

Imagine a function below like this:

<html>
<head>
    <title>JavaScript Promise error Handling example</title>
</head>
<body>
    <script>
        function foo(arg) {
            if (typeof arg != 'number' || arg <= 0) {
                throw new Error('Invalid arg argument')
            }
            return new Promise((resolve, reject) =>
                setTimeout(() =>
                    resolve(arg + ' ' + 'completed'), 1000)
            )
        }

        foo('fdfd')
            .then(result => console.log(result))
            .catch(err => console.log(err)) // <-- Error: Invalid argument will be caught here
    </script>
</body>
</html>

Output:

JavaScript Promise Error Handling with Examples

In the above example foo() function throw an error outside the promise, which gets handled by using both then() and catch() methods.

Raise an exception outside the promise

When we raise an exception outside the promise, we must catch it with try/catch.

<html>
<head>
    <title>JavaScript Promise error handling with try catch example</title>
</head>
<body>
    <script>
        function foo(arg) {
            if (typeof arg != 'number' || arg <= 0) {
                throw new Error('Invalid arg argument')
            }
            return new Promise((resolve, reject) =>
                setTimeout(() =>
                    resolve(arg + ' ' + 'completed'), 1000)
            )
        }

        try {
            foo('alphnumberic')
                .then(result => console.log(result))
                .catch(err => console.log(`Caught by .catch ${error}`));
        } catch (error) {
            console.log(`Caught by try/catch ${error}`);
        }
    </script>
</body>
</html>

Output:

Raise an exception outside the promise

Throw an error inside the Promises

Inside the promise, the catch() method will catch the error caused by the throw statement and reject(). We have modified the existing function so as to throw an error inside the promises and then consume the promise.

<html>
<head>
    <title>JavaScript throw an error inside the Promises example</title>
</head>
<body>
    <script>
        let isValid = false;
        function foo(arg) {
            return new Promise((resolve, reject) => {
                if (!isValid) {
                    throw new Error('Invalid argument is passed to function')
                }
                setTimeout(() =>
                    resolve(arg + ' ' + 'completed'), 1000)
            })
        }

        try {
            foo('alphnumberic')
                .then(result => console.log(result))
                .catch(error => console.log(`Caught by .catch ${error}`));
        } catch (error) {
            console.log(`Caught by try/catch ${error}`);
        }
    </script>
</body>
</html>

Output:

Throw an error inside the Promises

If we throw an error inside the promises the catch() method will catch the error, not by the try/catch.

Calling reject() method of Promise inside the promise

reject() method returns a promise that is rejected. It is highly used for debugging purposes and error catching. We have modified the existing function so as to throw an error by calling reject() method. As throwing an error has the same impact as calling the reject() method that has elaborated in the below example:

<html>
<head>
    <title>JavaScript throw an error by calling reject() method example</title>
</head>
<body>
    <script>
        let isValid = false;
        function foo(arg) {
            return new Promise((resolve, reject) => {
                if (!isValid) {
                    reject('Invalid argument is passed to function')
                }
                setTimeout(() =>
                    resolve(arg + ' ' + 'completed'), 1000)
            })
        }

        try {
            foo('alphnumberic')
                .then(result => console.log(result))
                .catch(error => console.log(`Caught by .catch ${error}`));
        } catch (error) {
            console.log(`Caught by try/catch ${error}`);
        }
    </script>
</body>
</html>

Output:

Calling reject() method of Promise inside the promise

In the above example rather than throwing an error inside the promise, we have called the reject() method of promise explicitly. In this case catch() method also handles the error as it handles in throwing an error inside the promises.

Unhandled rejected by missing the catch() method

An error will be silently ignored if a promise doesn’t have a catch() block or reject() handler. If any error occurs and we don’t have the catch() method, the JavaScript engine issues a runtime error and stops the execution of the program.

<html>
<head>
    <title>JavaScript missing the catch()method example</title>
</head>
<body>
    <script>
        let isValid = false;
        function foo(arg) {
            return new Promise((resolve, reject) => {
                if (!isValid) {
                    reject('Invalid argument is passed to function')
                }
                setTimeout(() =>
                    resolve(arg + ' ' + 'completed'), 1000)
            })
        }

        try {
            foo('alphnumberic')
                .then(result => console.log(result))//this will not execute
                //.catch(error => console.log(`Caught by .catch ${error}`));
        } catch (error) {
            console.log(`Caught by try/catch ${error}`);
        }
    </script>
</body>
</html>

Output:

Unhandled rejected by missing the catch() method

Chaining a Promise

If we have a promise chain then an error occurred in any promises, the catch() method will catch it.

<html>
<head>
    <title>JavaScript error handing chaining a promise example</title>
</head>
<body>
    <script>
        function foo(arg) {
            return new Promise((resolve, reject) => {
                if (typeof arg === 'undefined') {
                    throw new Error('Invalid argument is passed to function')
                }
                setTimeout(() =>
                    resolve(arg + ' ' + 'completed'), 1000)
            })
        }

        foo('dsds') //promise1
            .then(result => foo())  //promise2
            .then(result => foo('dsds')) //promise3
            .then(result => foo('dsds')) //promise4
            .catch(error => console.log(`Caught by .catch ${error}`));
    </script>
</body>
</html>

Output:

JavaScript Promise Error Handling with Examples

In the above example if any error occurred in Promise1, promise2, promise3, or promise4 then it will catch by catch() method.

In the next article, I am going to discuss JavaScript Async Await with Examples. Here, in this article, I try to explain the JavaScript Promise Error Handling with Examples. I hope this JavaScript Promise Error Handling with Examples article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this JavaScript Promise Error Handling.

Leave a Reply

Your email address will not be published. Required fields are marked *