DEV Community

Cover image for How do you handle errors consistently across a Node.js API?
Sneha M K
Sneha M K

Posted on

How do you handle errors consistently across a Node.js API?

Define a base AppError class with a status code and error code, then subclass it for specific errors (NotFoundError, ValidationError, UnauthorizedError). Register a global error-handling middleware in Express (or exception filter in NestJS) that catches everything, logs it, and returns a consistent error response shape:

`class AppError extends Error {
  constructor(
    public message: string,
    public statusCode: number,
    public code: string
  ) { super(message); }
}

// Global handler
app.use((err, req, res, next) => {
  if (err instanceof AppError) {
    return res.status(err.statusCode).json({ error: err.code, message: err.message });
  }
  // Unexpected error
  logger.error(err);
  res.status(500).json({ error: 'INTERNAL_ERROR' });
});`
Enter fullscreen mode Exit fullscreen mode

Top comments (0)