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
}
});
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
});
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
}
}
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
});
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.