DEV Community

Sam
Sam

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 (0)