Node.js

Error Handling in Node.js and Express: Practical Best Practices

5 min read R Square IT Support TeamSample article

Unhandled errors crash servers and confuse users. Learn a clean, centralised approach to error handling in Express APIs.

Consistent error handling makes APIs predictable for frontend developers and easier to debug for you. Express supports a special error-handling middleware with four arguments.

A centralised error handler

javascript
class AppError extends Error {
  constructor(message, status = 500) {
    super(message);
    this.status = status;
  }
}

// Register after all routes
app.use((err, req, res, next) => {
  const status = err.status || 500;
  res.status(status).json({
    message: status === 500 ? 'Something went wrong' : err.message,
  });
});

Handling async route errors

Express 5 forwards rejected promises from async handlers to the error middleware automatically. In Express 4, wrap async handlers or call next(err) inside a try/catch.

Best practices

  • Return meaningful HTTP status codes (400, 401, 403, 404, 409, 500)
  • Never leak stack traces or internal details to clients in production
  • Log errors with enough context to reproduce them
  • Validate input early and return clear validation messages
  • Node.js
  • Express
  • Error Handling

This is a sample article published as a starter resource. Verify technical details against official documentation for the versions you use.

Prepare. Perform. Progress.

Want personal guidance on this topic?

Our team can help you prepare, solve doubts and practise interviews around what you are learning.

Chat with us