@ticatec/express-exception
v1.1.3
Published
A comprehensive set of reusable error classes and middleware for Node.js Express applications with standardized error handling and consistent response formats.
Downloads
64
Readme
@ticatec/express-exception
中文 | English
A comprehensive set of reusable error classes and middleware for Node.js Express applications. This library provides standardized error handling with consistent response formats and proper HTTP status codes.
Features
- Standardized Error Types: Five predefined error classes for common application scenarios
- Express Middleware: Ready-to-use error handling middleware
- Consistent Response Format: Uniform JSON error responses with detailed information
- Development Support: Stack trace inclusion in development environments
- TypeScript Support: Full TypeScript definitions included
- Logging Integration: Built-in log4js integration for error tracking
Installation
npm install @ticatec/express-exceptionError Types
AppError
Generic application error with custom error codes.
throw new AppError(1001, "Database connection failed");UnauthenticatedError
Thrown when unauthenticated users attempt to access protected resources (HTTP 401).
throw new UnauthenticatedError();InsufficientPermissionError
Thrown when authenticated users lack sufficient permissions (HTTP 403).
throw new InsufficientPermissionError();IllegalParameterError
Thrown when invalid or illegal parameters are provided (HTTP 400).
throw new IllegalParameterError("Email format is invalid");ActionNotFoundError
Thrown when requested routes or actions don't exist (HTTP 404).
throw new ActionNotFoundError();Usage
Basic Setup
import express from 'express';
import { handleError, AppError, UnauthenticatedError } from '@ticatec/express-exception';
const app = express();
// Your routes
app.get('/api/users', (req, res, next) => {
try {
// Your logic here
if (!req.headers.authorization) {
throw new UnauthenticatedError();
}
// ... more logic
} catch (error) {
next(error);
}
});
// Error handling middleware (must be last)
app.use((err, req, res, next) => {
handleError(err, req, res);
});
app.listen(3000);Error Response Format
All errors are returned in a consistent JSON format:
{
"code": -1,
"host": "192.168.1.100",
"client": "192.168.1.50",
"path": "/api/users",
"method": "GET",
"timestamp": 1699123456789,
"message": "Unauthenticated user is accessing the system.",
"stack": "Error: ... (only in development)"
}Response Fields
- code: Application-specific error code (-1 for generic errors)
- host: Server IP address
- client: Client IP address
- path: Full request path
- method: HTTP method
- timestamp: Unix timestamp in milliseconds
- message: Human-readable error message (null if not available)
- stack: Stack trace (only included in development environments)
Development vs Production
Stack traces are automatically included when the request header env is set to development or dev:
// Client request with development header
fetch('/api/users', {
headers: {
'env': 'development'
}
});HTTP Status Code Mapping
| Error Type | HTTP Status | Description | |------------|-------------|-------------| | UnauthenticatedError | 401 | Unauthorized access | | InsufficientPermissionError | 403 | Forbidden - insufficient permissions | | IllegalParameterError | 400 | Bad Request - invalid parameters | | ActionNotFoundError | 404 | Not Found - route/action doesn't exist | | AppError | 500 | Internal Server Error - application-specific | | Other errors | 500 | Internal Server Error - unexpected errors |
Dependencies
Peer Dependencies
- log4js (^6.7.0): Required for error logging functionality
Runtime Dependencies
- ip (^1.1.8): Used for IP address detection
TypeScript Support
This library is written in TypeScript and includes full type definitions. All error classes and the error handler function are properly typed.
import { AppError, handleError } from '@ticatec/express-exception';
import { Request, Response, NextFunction } from 'express';
// TypeScript will provide full intellisense and type checking
const errorMiddleware = (err: Error, req: Request, res: Response, next: NextFunction) => {
handleError(err, req, res);
};License
MIT
Contributing
Issues and pull requests are welcome. Please visit the GitHub repository for more information.
Author
Henry Feng
