Dung (Donny) Nguyen

Senior Software Engineer

Error Handling

In Node.js, error handling is critical due to its asynchronous nature. Here’s an overview of common techniques:

1. Try-Catch Blocks

   function syncFunction() {
       try {
           // some synchronous code
       } catch (error) {
           console.error("Caught an error:", error);
       }
   }
   
   async function asyncFunction() {
       try {
           await someAsyncOperation();
       } catch (error) {
           console.error("Caught async error:", error);
       }
   }

2. Error-First Callbacks

   function readFileCallback(err, data) {
       if (err) {
           console.error("Error reading file:", err);
       } else {
           console.log("File data:", data);
       }
   }

   fs.readFile("path/to/file", "utf8", readFileCallback);

3. Handling Rejected Promises

   // Using .catch() method
   someAsyncOperation()
       .then(result => {
           console.log("Operation successful:", result);
       })
       .catch(error => {
           console.error("Error caught in .catch():", error);
       });

   // Global rejection handler
   process.on("unhandledRejection", error => {
       console.error("Unhandled promise rejection:", error);
   });

Best Practices Summary

Combining these techniques ensures robust error handling across different types of code in Node.js.