Not Found Handler
The Not Found Handler component provides a centralized and consistent way to handle unmatched routes.
Instead of allowing undefined routes to return inconsistent responses or default Express errors, this component ensures that all unknown endpoints respond with a standardized 404 Not Found error.
This component exists to:
- Catch all requests to undefined routes
- Return a predictable and structured 404 response
- Integrate seamlessly with Servercn error handling
- Improve API reliability and developer experience
Installation Guide
This component requires additional Servercn components.
👉 You do not need to install any Servercn components manually. Running this component installer will automatically install all required components. Manual installation is optional and only recommended if you prefer fine-grained components control
1. Install Servercn components(Optional)
- API Error Handler:
npx servercn-cli add error-handlerDocumentation: API Error Handler
⚠️ If this dependency is not installed, the component will not function correctly.
2. Install this component
npx servercn-cli add not-found-handlerThis 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.
1. MVC Structure
src/middlewares/not-found-handler.ts
2. Feature Structure
src/shared/middlewares/not-found-handler.ts
Usage Example
The Not Found Handler must be placed after all routes but before the error handler in your Express application.
1. MVC Structure
src/app.ts
2. Feature Structure
src/app.ts
Response Format
When a route is not found, the handler returns a standardized 404 response:
The exact format depends on your ApiError and ApiResponse configuration.
How It Works
- Route Matching: Express processes routes in the order they are defined
- Catch-All: The Not Found Handler is placed after all defined routes
- Error Throwing: When a request doesn't match any route, it reaches the Not Found Handler
- Error Propagation: The handler throws an
ApiErrorwith a 404 status code - Error Handling: The global error handler catches the error and returns a standardized response
Best Practices
- Use
ApiError.notFound()for consistency - Always place the Not Found Handler after all route definitions
- Always place the Not Found Handler before the global error handler
- The handler will catch all HTTP methods (GET, POST, PUT, DELETE, etc.)
- Customize the error message to include the method and path for better debugging
Why This Component Matters
Without a dedicated not found handler:
- Undefined routes may return HTML error pages
- Error responses become inconsistent
- Debugging API issues becomes harder
This component ensures:
- All API endpoints return JSON
- Status codes are correct and explicit
- Errors are handled uniformly