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
This component requires additional Servercn components.
👉 Note: You do not need to install any servercn dependencies manually. Installing this component will automatically install all required servercn dependencies. Manual installation is optional if you prefer to manage dependencies yourself.
1. Install Servercn components(Optional)
- HTTP Status Codes:
npx servercn-cli add http-status-codesDocumentation: HTTP Status Codes
- Api Error Handler:
npx servercn-cli add error-handlerDocumentation: Api Error Handler
- Logger:
npx servercn-cli add logger-pinoDocumentation: Logger
2. Install this component
npx servercn-cli add global-error-handler⚠️ If this dependency is not installed, the component will not function correctly.
Why 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