Global Error Handling
A global error handler is a core part of any production-ready Express application.
It ensures that all errors—expected or unexpected—are handled consistently, securely, and predictably.
Servercn provides a structured approach using:
ApiErrorfor operational errorsApiResponsefor consistent responsesSTATUS_CODESfor standardized HTTP status codes- Express error middleware for central handling
Installation Guide
npx servercn-cli add global-error-handlerWhy a Global Error Handler?
Without a global error handler:
- Errors leak stack traces to clients
- Response formats become inconsistent
- Debugging and logging are fragmented
- Async errors may crash the process
With a global error handler:
- One place to handle all errors
- Consistent API response shape
- Clear separation of operational vs programmer errors
- Easier logging and monitoring
Error Flow in Servercn
- Route or service throws an error (ApiError or native error)
- Error bubbles through AsyncHandler
- Express forwards it to the global error middleware
- The middleware formats and sends a standardized response
Prerequisites
Ensure the following environment variables are defined:
Ensure the following configuration are defined:
src/configs/env.ts
Basic Implementation
1. MVC Structure
src/middlewares/error-handler.ts
1. Feature Structure
src/shared/middlewares/error-handler.ts
Usage Example
src/app.ts