Handling errors in Node.js, whether synchronous or asynchronous, is crucial for building robust applications. Here's how you can handle both types of errors:
Synchronous Errors : Synchronous errors occur when there is an exception thrown during the execution of synchronous code. To handle these errors, you can use try-catch blocks.
Asynchronous Errors : Asynchronous errors occur when there is an error in asynchronous operations such as callbacks, promises, or async/await functions. Here are different ways to handle asynchronous errors
//Synchronous Errors
try {
// Synchronous code that might throw an error
const result = someSynchronousFunction();
} catch (error) {
// Handle the error
console.error('An error occurred:', error.message);
}
//Asynchronous Errors
//Callbacks
someAsyncFunction((error, result) => {
if (error) {
console.error('An error occurred:', error.message);
return;
}
// Handle the result
});
//Promises
someAsyncFunction()
.then(result => {
// Handle the result
})
.catch(error => {
console.error('An error occurred:', error.message);
});
//Async/Await
async function fetchData() {
try {
const result = await someAsyncFunction();
// Handle the result
} catch (error) {
console.error('An error occurred:', error.message);
}
}
//Global Error Handling
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error.message);
// Gracefully shut down the application
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
// Handle or log the error
});
© www.thecoderjob.com. All Rights Reserved. Designed by HTML Codex