Node.js Error Handling: Best Practices

Node.js error handling can be tricky, especially with async code. Here’s how to do it properly.

Sync vs Async Errors

// Sync - try/catch works
try {
  JSON.parse(invalidJson);
} catch (err) {
  console.error(err);
}

// Async - need different approach
async function fetchData() {
  try {
    const data = await fetch(url);
    return data.json();
  } catch (err) {
    throw new Error('Failed to fetch');
  }
}

Express Error Middleware

// Error handling middleware (4 arguments)
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(err.status || 500).json({
    error: process.env.NODE_ENV === 'production' 
      ? 'Something went wrong' 
      : err.message
  });
});

Custom Error Classes

class NotFoundError extends Error {
  constructor(message) {
    super(message);
    this.status = 404;
  }
}

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.