Open In App

How to handle errors when dealing with asynchronous code ?

Last Updated : 04 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Asynchronous code in Node.js is a code that does not block the execution of code after it. In Synchronous code, the code waits for further code execution until the current operation is not completed and executes from top to down while in asynchronous code, the asynchronous code is executed in a separate thread so that execution of further code is not blocked and thus they are both executed simultaneously. To get a deeper understanding of Asynchronous programming, refer How does asynchronous code work in JavaScript?

Now let us discuss how to handle errors in Asynchronous Code.

Using CallBacks: A Callback Function is a function that is passed as the last parameter in an asynchronous function and a callback is called when the asynchronous function has been executed. The first parameter in any callback function is the error object so they are often referred to as error-first callbacks. If there is no error, the error object is null otherwise it will contain information regarding the error. 

Example: In the example below, we use the setTimeout method to make our mod function asynchronous. If b is zero we pass an error saying “Modulo zero is not allowed” otherwise we log the result. This way our callback handles errors every time the mod function is called.

Javascript




<script>
    const mod = (a, b, callback) => {
        setTimeout(() => {
            if (b == 0) {
                // Error
                callback("Modulo zero is not allowed");
            } else {
                // Success
                callback(null, a % b);
            }
        }, 0);
    };
 
    // 5 mod 2 will give result 1
    mod(5, 2, (err, res) => {
        if (err) {
            console.log(err);
        }
        else {
            console.log('The result is ' + res);
        }
    });
 
    // 5 mod 0 will give error
    mod(5, 0, (err, res) => {
        if (err) {
            console.log(err);
        }
        else {
            console.log(`The result is ${res}`);
        }
    });
</script>


Output:

The result is 1
Modulo zero is not allowed

But when we use the callback method we can sometimes get stuck in callback hell. To avoid that we use Promises discussed below.

Using Promises: Promises enable us to handle asynchronous operations in Nodejs without getting stuck in callback hell. A promise is either resolved or rejected. There are two methods then() and catch() after a promise is resolved or rejected. If it is resolved then code in the then() method is executed otherwise we get the error thrown through the catch block.

Example: let us modify the example above and handle errors using promises.

Javascript




<script>
    const mod = (a, b) => {
        return new Promise((resolve, reject) => {
            if (b == 0) {
                // Rejected (error)
                reject("Modulo zero is not allowed");
            } else {
                //Resolved (Success)
                resolve(a % b);
            }
        })
    };
 
    // 5 mod 2 will give result 1
    mod(5, 2).then((res) => {
        console.log(`The result is ${res}`);
    }).catch((err) => {
        console.log(err);
    });
 
    // 5 mod 0 will give error
    mod(5, 0).then((res) => {
        console.log(`The result is ${res}`);
    }).catch((err) => {
        console.log(err);
    });
</script>


Output:

The result is 1
Modulo zero is not allowed

The code is cleaner now than before when we were using callbacks. Although Promises enabled us to prevent callback hells they have syntax complexity of their own so we got Async functions discussed below.

Using Async/Await: Async/Await makes JavaScript promises easier to work with. It enables us to handle errors using the try-catch block. To use async-await, we just need to create an async function in which we will implement our try-catch block. In the try block, we will await our promise to be completed. If it gets resolved we will get the result otherwise an error will be thrown through the catch block. Await can only be used inside an async function or async callback or async arrow function.

Example: 

Javascript




<script>
    const mod = (a, b) => {
        return new Promise((resolve, reject) => {
            if (b == 0) {
                // Rejected (error)
                reject("Modulo zero is not allowed");
            } else {
                //Resolved (Success)
                resolve(a % b);
            }
        });
    };
 
    // 5 mod 2 will give result 1
    async function _5mod2() {
        try {
            const res = await mod(5, 2);
            console.log(`The result of division is ${res}`);
        } catch (err) {
            console.log(err);
        }
    };
    _5mod2();
 
    // 5 mod 0 will give error
    async function _5mod0() {
        try {
            const res = await mod(5, 0);
            console.log(`The result of division is ${res}`);
        } catch (err) {
            console.log(err);
        }
    };
    _5mod0();
</script>


Output:

The result of division is 1
Modulo zero is not allowed


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

Similar Reads