🚨 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…


This content originally appeared on DEV Community and was authored by Prathviraj H

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");
});

Frontend response (❌ Incorrect)

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

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;

Now, I could throw errors like this:

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

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

âś… 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);

Now, API Errors Return JSON

Frontend response (âś… Correct)

{
    "success": false,
    "message": "Invalid Request"
}

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.


This content originally appeared on DEV Community and was authored by Prathviraj H


Print Share Comment Cite Upload Translate Updates
APA

Prathviraj H | Sciencx (2025-03-08T18:12:13+00:00) 🚨 Fixing API Error Handling in Express – No More HTML Errors!. Retrieved from https://www.scien.cx/2025/03/08/%f0%9f%9a%a8-fixing-api-error-handling-in-express-no-more-html-errors/

MLA
" » 🚨 Fixing API Error Handling in Express – No More HTML Errors!." Prathviraj H | Sciencx - Saturday March 8, 2025, https://www.scien.cx/2025/03/08/%f0%9f%9a%a8-fixing-api-error-handling-in-express-no-more-html-errors/
HARVARD
Prathviraj H | Sciencx Saturday March 8, 2025 » 🚨 Fixing API Error Handling in Express – No More HTML Errors!., viewed ,<https://www.scien.cx/2025/03/08/%f0%9f%9a%a8-fixing-api-error-handling-in-express-no-more-html-errors/>
VANCOUVER
Prathviraj H | Sciencx - » 🚨 Fixing API Error Handling in Express – No More HTML Errors!. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/03/08/%f0%9f%9a%a8-fixing-api-error-handling-in-express-no-more-html-errors/
CHICAGO
" » 🚨 Fixing API Error Handling in Express – No More HTML Errors!." Prathviraj H | Sciencx - Accessed . https://www.scien.cx/2025/03/08/%f0%9f%9a%a8-fixing-api-error-handling-in-express-no-more-html-errors/
IEEE
" » 🚨 Fixing API Error Handling in Express – No More HTML Errors!." Prathviraj H | Sciencx [Online]. Available: https://www.scien.cx/2025/03/08/%f0%9f%9a%a8-fixing-api-error-handling-in-express-no-more-html-errors/. [Accessed: ]
rf:citation
» 🚨 Fixing API Error Handling in Express – No More HTML Errors! | Prathviraj H | Sciencx | https://www.scien.cx/2025/03/08/%f0%9f%9a%a8-fixing-api-error-handling-in-express-no-more-html-errors/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.