DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

Essential Strategies for Handling Errors and Exceptions in Node.js Applications

Proper error and exception handling is critical for building stable Node.js applications. Here’s how you can handle errors effectively:

1. Use Try-Catch for Synchronous Code

  • Useful for code that doesn’t use callbacks or Promises.
  • Example:
try {
  // Synchronous code that may throw
  let data = fs.readFileSync('file.txt');
} catch (err) {
  console.error('Error reading file:', err);
}
Enter fullscreen mode Exit fullscreen mode

2. Handle Errors in Callbacks

  • Always check for the first err argument in callbacks.
  • Example:
fs.readFile('file.txt', (err, data) => {
  if (err) {
    console.error('Error:', err);
    return;
  }
  console.log('File data:', data);
});
Enter fullscreen mode Exit fullscreen mode

3. Manage Promises and Async/Await Errors

  • Use .catch() for Promises and try-catch for async functions.
  • Example:
// Promise
readFileAsync('file.txt')
  .then(data => console.log(data))
  .catch(err => console.error('Promise error:', err));

// Async/Await
async function readFile() {
  try {
    let data = await readFileAsync('file.txt');
    console.log(data);
  } catch (err) {
    console.error('Async/Await error:', err);
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Handle Uncaught Exceptions and Unhandled Rejections

  • Use process events to log and shut down gracefully.
  • Example:
process.on('uncaughtException', err => {
  console.error('Uncaught Exception:', err);
  process.exit(1);
});

process.on('unhandledRejection', reason => {
  console.error('Unhandled Rejection:', reason);
  process.exit(1);
});
Enter fullscreen mode Exit fullscreen mode

5. Use Error Middleware in Express

  • Handle errors efficiently in web APIs.
  • Example:
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});
Enter fullscreen mode Exit fullscreen mode

Summary: Always handle errors at every layer—synchronous, callback, promise, and process level. This keeps your Node.js applications resilient and maintainable.

Top comments (0)