View as Json

Not Found Handler

The Not Found Handler component provides a centralized and consistent way to handle unmatched routes.


Installation Guide

npx servercn-cli add not-found-handler

This component requires the API Error Handler component to function correctly.


Basic Implementation

The Not Found Handler is a middleware that catches all unmatched routes and throws a standardized 404 error.

src/middlewares/not-found-handler.ts
import { Request, Response, NextFunction } from "express";
import { ApiError } from "../utils/api-error";
 
export const notFoundHandler = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  throw ApiError.notFound(`Route ${req.method} ${req.originalUrl} not found`);
};

Usage Example

The Not Found Handler must be placed after all routes but before the error handler in your Express application.

src/app.ts
import express, { type Application } from "express";
import { errorHandler } from "./middlewares/error-handler";
import { notFoundHandler } from "./middlewares/not-found-handler";
 
const app: Application = express();
 
app.use(express.json());
 
// routes here
// ...
 
// Not found handler (should be after routes)
app.use(notFoundHandler);
 
// Global error handler (should be last)
app.use(errorHandler);
 
export default app;

Response Format

When a route is not found, the handler returns a standardized 404 response:

{
  "success": false,
  "message": "Route GET /api/v1/invalid-route not found",
  "statusCode": 404
}

The exact format depends on your ApiError and ApiResponse configuration.


How It Works

  1. Route Matching: Express processes routes in the order they are defined
  2. Catch-All: The Not Found Handler is placed after all defined routes
  3. Error Throwing: When a request doesn't match any route, it reaches the Not Found Handler
  4. Error Propagation: The handler throws an ApiError with a 404 status code
  5. Error Handling: The global error handler catches the error and returns a standardized response

File & Folder Structure

Loading files...

Installation

npx servercn-cli add not-found-handler