To handle errors in the correct way when writing asynchronous code in Node.js, there are a few techniques used in different situations:
Error-First Callbacks: This is a common pattern in Node.js. In this pattern, the callback function receives an error as its first argument. When an error occurs, the callback is called with the error object; otherwise, it continues with the data.
For example:
fs.readFile('/non-existent-file', (err, data) => {
if (err) {
console.error('Error:', err);
} else {
console.log('Data:', data);
}
});
Promises and .catch(): When working with Promises, you can handle errors by chaining a .catch() method. This catches any errors that occur in the Promise chain:
somePromiseFunction()
.then(result => console.log(result))
.catch(err => console.error('Error:', err));
Global Error Handling: It is possible to catch an uncaught exception or any unhandled promise rejection, using global event handlers like this in Node.js:
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);});