Error handling is important for building reliable APIs.

When handling errors in Express, it’s important to send the correct HTTP status code and a helpful error message. As we’ve just seen, we use res.status() to set the status code for the response. After setting the status, we usually send a JSON object with an error property to explain what went wrong.

In the above example we used this code to return a 404 when no product was found:

Example:

if (!product) {
  return res.status(404).json({ error: "Product not found" });
}
  • res.status(404) sets the HTTP status code to 404.
  • .json({ error: 'Product not found' }) sends a JSON response with an error message.
  • This pattern helps clients (like your frontend) understand what went wrong and respond appropriately.

It’s important to always handle errors in your API so users and developers get clear feedback when something goes wrong.

  • Always check if the requested resource exists.
  • Return the correct status code for errors.
  • Send a helpful error message in the response.

Other common error codes and patterns:

400 Bad Request - Invalid input data Use when the user sends data in the wrong format or type:

app.get("/users/:id", (req, res) => {
  const id = Number(req.params.id);
  if (isNaN(id)) {
    return res.status(400).json({ error: "Invalid user ID" });
  }
  // ...
});

401 Unauthorized - Missing or invalid authentication Use when the user needs to log in first:

app.get("/profile", (req, res) => {
  const token = req.headers.authorization;
  if (!token) {
    return res.status(401).json({ error: "Authentication required" });
  }
  // ...
});

403 Forbidden - Authenticated but not authorized Use when the user is logged in but doesn’t have permission:

app.delete("/admin/users/:id", (req, res) => {
  if (req.user.role !== "admin") {
    return res.status(403).json({ error: "Admin access required" });
  }
  // ...
});

422 Unprocessable Entity - Valid format but invalid data Use when data format is correct but content is invalid:

app.post("/users", (req, res) => {
  const { email } = req.body;
  if (email && !email.includes("@")) {
    return res.status(422).json({ error: "Invalid email format" });
  }
  // ...
});

500 Internal Server Error

  • This status code is returned when something unexpected goes wrong on the server
  • Usually happens due to unhandled exceptions or database connection issues
  • Express automatically returns 500 for unhandled errors
Tags: