DEV Community

Prathviraj H
Prathviraj H

Posted on

🚨 Fixing API Error Handling in Express – No More HTML Errors!

The Issue

While developing my CampusX project, I built a custom error-handling class, ApiError, to standardize error messages.

βœ… Errors were thrown properly in the backend.

❌ But on the frontend, I received an HTML error page instead of a JSON response.

This made it impossible to handle errors correctly in my React app.


The Root Cause

By default, Express sends HTML error pages when an unhandled error occurs.

Example:

app.get("/error-route", (req, res) => {
    throw new Error("Something went wrong");
});
Enter fullscreen mode Exit fullscreen mode

Frontend response (❌ Incorrect)

<!DOCTYPE html>
<html lang="en">
<head><title>Error</title></head>
<body><h1>Internal Server Error</h1></body>
</html>
Enter fullscreen mode Exit fullscreen mode

I needed a way to always return JSON responses for errors.

The Fix – Creating a Custom API Error Handler

βœ… Step 1: Create an ApiError Class

I created a reusable error class for consistent error messages:

class ApiError extends Error {
    constructor(statusCode, message) {
        super(message);
        this.statusCode = statusCode;
    }
}

module.exports = ApiError;
Enter fullscreen mode Exit fullscreen mode

Now, I could throw errors like this:

const ApiError = require("./ApiError");

app.get("/error-route", (req, res) => {
    throw new ApiError(400, "Invalid Request");
});

Enter fullscreen mode Exit fullscreen mode

βœ… Step 2: Create a Global Error Middleware

To ensure Express sends JSON responses for errors, I added this middleware:

const errorHandler = (err, req, res, next) => {
    const statusCode = err.statusCode || 500;
    return res.status(statusCode).json({
        success: false,
        message: err.message || "Internal Server Error",
    });
};

// Register this middleware at the end of all routes
app.use(errorHandler);
Enter fullscreen mode Exit fullscreen mode

Now, API Errors Return JSON

Frontend response (βœ… Correct)

{
    "success": false,
    "message": "Invalid Request"
}
Enter fullscreen mode Exit fullscreen mode

No more HTML errorsβ€”now the frontend gets a structured JSON response that can be handled properly! πŸš€

Key Takeaways

  • Express sends HTML error pages by default when an error occurs.
  • A global error middleware ensures that errors return JSON responses.
  • Custom error classes like ApiError help maintain consistency in error handling.

Top comments (0)