@ticatec/express-exception
Version:
A comprehensive set of reusable error classes and middleware for Node.js Express applications with standardized error handling and consistent response formats.
176 lines (131 loc) • 5.01 kB
Markdown
# @ticatec/express-exception
[中文](./README_CN.md) | English
[](https://www.npmjs.com/package/@ticatec/express-exception)
[](https://opensource.org/licenses/MIT)
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
```bash
npm install @ticatec/express-exception
```
## Error Types
### AppError
Generic application error with custom error codes.
```javascript
throw new AppError(1001, "Database connection failed");
```
### UnauthenticatedError
Thrown when unauthenticated users attempt to access protected resources (HTTP 401).
```javascript
throw new UnauthenticatedError();
```
### InsufficientPermissionError
Thrown when authenticated users lack sufficient permissions (HTTP 403).
```javascript
throw new InsufficientPermissionError();
```
### IllegalParameterError
Thrown when invalid or illegal parameters are provided (HTTP 400).
```javascript
throw new IllegalParameterError("Email format is invalid");
```
### ActionNotFoundError
Thrown when requested routes or actions don't exist (HTTP 404).
```javascript
throw new ActionNotFoundError();
```
## Usage
### Basic Setup
```javascript
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:
```json
{
"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`:
```javascript
// 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.
```typescript
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](https://github.com/ticatec/node-library/tree/main/ticatec-express-exception) for more information.
## Author
Henry Feng
## Repository
[https://github.com/ticatec/node-library](https://github.com/ticatec/node-library)