How to Handle Async Errors in Node.js?

1. Definition

Async errors occur during asynchronous operations like file handling, API calls, or database queries. These errors must be handled properly to prevent application crashes.

2. Using Callbacks (Error-first pattern)

const fs = require("fs");

fs.readFile("file.txt", (err, data) => {
  if (err) {
    console.error("Error:", err.message);
    return;
  }
  console.log(data.toString());
});

3. Using Promises (.catch)

const fs = require("fs").promises;

fs.readFile("file.txt", "utf8")
  .then(data => console.log(data))
  .catch(err => console.error("Error:", err.message));

4. Using Async/Await (try...catch)

const fs = require("fs").promises;

async function readFile() {
  try {
    const data = await fs.readFile("file.txt", "utf8");
    console.log(data);
  } catch (err) {
    console.error("Error:", err.message);
  }
}

readFile();

5. Best Practices

  • Always handle errors in async code
  • Use try...catch with async/await
  • Use .catch() for promises
  • Avoid unhandled promise rejections

6. Advantages

  • Prevents application crashes
  • Improves reliability
  • Better debugging
  • Cleaner and maintainable code