refactor: 重构项目目录与代码结构,清理冗余文件
本次提交进行了大规模的项目结构调整: 1. 调整文件目录归属,将模块代码按功能域重新组织 2. 删除多处冗余的DTO、实体类和模块文件 3. 统一了常量、装饰器、工具类的存放位置 4. 修复了`.gitignore`的日志目录匹配规则 5. 新增了健康检查、认证、用户、剧集、订单等核心业务模块
This commit is contained in:
79
filters/http.filter.ts
Normal file
79
filters/http.filter.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { Request, Response } from 'express';
|
||||
import { LogsService } from '../../modules/logs/logs.service';
|
||||
import { getRequestCost } from '../utils/request-context.util';
|
||||
|
||||
@Catch()
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
constructor(private readonly logsService: LogsService) {}
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const request = ctx.getRequest<
|
||||
Request & { requestId?: string; adminId?: number; user?: { id: number } }
|
||||
>();
|
||||
const response = ctx.getResponse<Response>();
|
||||
const statusCode =
|
||||
exception instanceof HttpException
|
||||
? exception.getStatus()
|
||||
: HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
const message = this.getMessage(exception, statusCode);
|
||||
const requestId = request.requestId ?? '';
|
||||
const costMs = getRequestCost(request);
|
||||
|
||||
this.logsService.recordRequest({
|
||||
requestId,
|
||||
method: request.method,
|
||||
path: request.originalUrl ?? request.url,
|
||||
query: request.query,
|
||||
body: request.body,
|
||||
statusCode,
|
||||
responseCode: statusCode,
|
||||
message,
|
||||
costMs,
|
||||
userId: request.user?.id,
|
||||
adminId: request.adminId,
|
||||
ip: request.ip,
|
||||
userAgent: request.get('user-agent'),
|
||||
errorStack: exception instanceof Error ? exception.stack : undefined,
|
||||
});
|
||||
|
||||
response.status(statusCode).json({
|
||||
code: statusCode,
|
||||
data: {},
|
||||
message,
|
||||
timestamp: Date.now(),
|
||||
requestId,
|
||||
cost: `${costMs}ms`,
|
||||
});
|
||||
}
|
||||
|
||||
private getMessage(exception: unknown, statusCode: number): string {
|
||||
if (exception instanceof HttpException) {
|
||||
const response = exception.getResponse();
|
||||
if (typeof response === 'string') {
|
||||
return response;
|
||||
}
|
||||
if (
|
||||
response &&
|
||||
typeof response === 'object' &&
|
||||
'message' in response
|
||||
) {
|
||||
const message = (response as { message: string | string[] }).message;
|
||||
return Array.isArray(message) ? message.join('; ') : message;
|
||||
}
|
||||
}
|
||||
|
||||
if (exception instanceof Error && statusCode === HttpStatus.INTERNAL_SERVER_ERROR) {
|
||||
return exception.message || 'Internal server error';
|
||||
}
|
||||
|
||||
return 'Internal server error';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user