NA +91-8727899942 thecoderjob@gmail.com

CHAPTER - 21

How to handling synchronous and asynchronous errors in node Js

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

Here's is the Code !!

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

Chapter 20

How to apply Role based access control in node Js

Previous chapter

Chapter 22

How to add custom error handling middleware in Node Js

Next chapter

Get In Touch

NA

thecoderjob@gmail.com

+91-8727899942

Popular Links

© www.thecoderjob.com. All Rights Reserved.               Designed by HTML Codex