Error Handling in Express.js

Gracefully managing unexpected failures in your backend

What is Error Handling?

Error handling is the process of catching and responding to unexpected issues that occur during execution—like invalid data, failed database queries, or broken APIs—without crashing the entire application.

Why is it Important?

How to Implement in Express?

  1. Use try...catch blocks for async operations.
  2. Use centralized error-handling middleware.
  3. Send proper status codes (like 400, 500) and messages.

Example: Basic Error Handling with try...catch

app.get("/user/:id", async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    if (!user) return res.status(404).json({ message: "User not found" });
    res.json(user);
  } catch (err) {
    res.status(500).json({ error: "Server Error" });
  }
});

Example: Centralized Error Handler

// middleware/errorHandler.js
function errorHandler(err, req, res, next) {
  console.error(err.stack);
  res.status(500).json({ message: "Something went wrong!" });
}
module.exports = errorHandler;

// Use it in server.js
const errorHandler = require('./middleware/errorHandler');
app.use(errorHandler);

When Should You Use It?

Implement error handling after your routes and logic are built, especially when:

Best Practices

References