@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.
173 lines (129 loc) • 4.58 kB
Markdown
中文 | [English](./README.md)
一个为 Node.js Express 应用程序提供的全面可重用错误类和中间件库。该库提供标准化的错误处理,具有一致的响应格式和适当的 HTTP 状态码。
- **标准化错误类型**:为常见应用场景预定义的五种错误类
- **Express 中间件**:开箱即用的错误处理中间件
- **一致的响应格式**:统一的 JSON 错误响应格式,包含详细信息
- **开发支持**:在开发环境中包含堆栈跟踪
- **TypeScript 支持**:包含完整的 TypeScript 类型定义
- **日志集成**:内置 log4js 集成用于错误跟踪
```bash
npm install @ticatec/express-exception
```
带有自定义错误代码的通用应用程序错误。
```javascript
throw new AppError(1001, "数据库连接失败");
```
当未经身份验证的用户尝试访问受保护资源时抛出(HTTP 401)。
```javascript
throw new UnauthenticatedError();
```
当经过身份验证的用户缺乏足够权限时抛出(HTTP 403)。
```javascript
throw new InsufficientPermissionError();
```
当提供无效或非法参数时抛出(HTTP 400)。
```javascript
throw new IllegalParameterError("邮箱格式无效");
```
当请求的路由或操作不存在时抛出(HTTP 404)。
```javascript
throw new ActionNotFoundError();
```
```javascript
import express from 'express';
import { handleError, AppError, UnauthenticatedError } from '@ticatec/express-exception';
const app = express();
// 你的路由
app.get('/api/users', (req, res, next) => {
try {
// 你的逻辑代码
if (!req.headers.authorization) {
throw new UnauthenticatedError();
}
// ... 更多逻辑
} catch (error) {
next(error);
}
});
// 错误处理中间件(必须放在最后)
app.use((err, req, res, next) => {
handleError(err, req, res);
});
app.listen(3000);
```
所有错误都以一致的 JSON 格式返回:
```json
{
"code": -1,
"host": "192.168.1.100",
"client": "192.168.1.50",
"path": "/api/users",
"method": "GET",
"timestamp": 1699123456789,
"message": "未经身份验证的用户正在访问系统",
"stack": "Error: ... (仅在开发环境中显示)"
}
```
- **code**: 应用程序特定的错误代码(通用错误为 -1)
- **host**: 服务器 IP 地址
- **client**: 客户端 IP 地址
- **path**: 完整的请求路径
- **method**: HTTP 方法
- **timestamp**: Unix 时间戳(毫秒)
- **message**: 人类可读的错误消息(如果不可用则为 null)
- **stack**: 堆栈跟踪(仅在开发环境中包含)
当请求头中的 `env` 设置为 `development` 或 `dev` 时,会自动包含堆栈跟踪:
```javascript
// 带有开发环境头的客户端请求
fetch('/api/users', {
headers: {
'env': 'development'
}
});
```
| 错误类型 | HTTP 状态码 | 描述 |
|----------|-------------|------|
| UnauthenticatedError | 401 | 未授权访问 |
| InsufficientPermissionError | 403 | 禁止访问 - 权限不足 |
| IllegalParameterError | 400 | 错误请求 - 参数无效 |
| ActionNotFoundError | 404 | 未找到 - 路由/操作不存在 |
| AppError | 500 | 内部服务器错误 - 应用程序特定 |
| 其他错误 | 500 | 内部服务器错误 - 意外错误 |
- **log4js** (^6.7.0):错误日志功能所需
- **ip** (^1.1.8):用于 IP 地址检测
该库使用 TypeScript 编写,包含完整的类型定义。所有错误类和错误处理函数都有适当的类型。
```typescript
import { AppError, handleError } from '@ticatec/express-exception';
import { Request, Response, NextFunction } from 'express';
// TypeScript 将提供完整的智能感知和类型检查
const errorMiddleware = (err: Error, req: Request, res: Response, next: NextFunction) => {
handleError(err, req, res);
};
```
MIT
欢迎提交 Issue 和 Pull Request。更多信息请访问 [GitHub 仓库](https://github.com/ticatec/node-library/tree/main/ticatec-express-exception)。
Henry Feng
[](https://github.com/ticatec/node-library)