The Ops Community ⚙️

Ofido Hub
Ofido Hub

Posted on

Handling asynchronous errors in JavaScript

A; Callbacks: This is one of the oldest ways to handle asynchronous operations in JavaScript. The convention is to make the first parameter of the callback an error object. If there is no error, the first parameter will be null.

fs.readFile('somefile.txt', (err, data) => {
    if (err) {
        // Handle the error
    } else {
        // Handle the data
    }
});
Enter fullscreen mode Exit fullscreen mode

B; Promises with .catch(): Promises are a common way to handle asynchronous operations in JavaScript. If an error occurs in a promise, it can be caught with .catch().

someAsyncFunction()
    .then(result => {
        // Handle the result
    })
    .catch(error => {
        // Handle the error
    });
Enter fullscreen mode Exit fullscreen mode

C; Async/Await with try/catch: Async/await is a more modern way to handle asynchronous operations. It allows you to write asynchronous code as if it were synchronous. However, to catch errors, you need to use a try/catch block.

async function someFunction() {
    try {
        const result = await someAsyncFunction();
        // Handle the result
    } catch (error) {
        // Handle the error
    }
}
Enter fullscreen mode Exit fullscreen mode

D; Event listeners: If you're working with EventEmitters (like in Node.js), you can listen for an 'error' event.

const emitter = getSomeEventEmitter();

emitter.on('error', (error) => {
    // Handle the error
});
Enter fullscreen mode Exit fullscreen mode

Finally; Remember, unhandled promise rejections are deprecated. In future versions of Node.js, unhandled promise rejections will terminate the process. So, always handle errors in promises.

Top comments (2)

Collapse
 
ruhi_parveen_9653173d9030 profile image
Ruhi Parveen

I really enjoyed your blog! The explanations of asynchronous error handling in JavaScript were clear and informative. It’s great to see the different approaches laid out so effectively. Thank you

you can also read more: What is Hierarchical Inheritance in Java? With Examples

Collapse
 
canopas_user profile image
Nandani Sharma

I'm glad you found the explanations on asynchronous error handling clear and informative.

It’s always great to know that the approach resonates with readers like you. 😊