diff --git a/backend/services/identity-service/src/shared/filters/global-exception.filter.ts b/backend/services/identity-service/src/shared/filters/global-exception.filter.ts index ce64c78f..05dad0fd 100644 --- a/backend/services/identity-service/src/shared/filters/global-exception.filter.ts +++ b/backend/services/identity-service/src/shared/filters/global-exception.filter.ts @@ -1,6 +1,6 @@ import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus, - Injectable, NestInterceptor, ExecutionContext, CallHandler, + Injectable, NestInterceptor, ExecutionContext, CallHandler, Logger, } from '@nestjs/common'; import { Response } from 'express'; import { Observable } from 'rxjs'; @@ -9,9 +9,12 @@ import { DomainError, ApplicationError } from '@/shared/exceptions/domain.except @Catch() export class GlobalExceptionFilter implements ExceptionFilter { + private readonly logger = new Logger(GlobalExceptionFilter.name); + catch(exception: unknown, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); + const request = ctx.getRequest(); let status = HttpStatus.INTERNAL_SERVER_ERROR; let message = '服务器内部错误'; @@ -37,6 +40,22 @@ export class GlobalExceptionFilter implements ExceptionFilter { message = exception.message; } + // 记录错误日志 + const errorLog = { + method: request.method, + url: request.url, + status, + message, + code, + stack: exception instanceof Error ? exception.stack : undefined, + }; + + if (status >= 500) { + this.logger.error(`Internal server error: ${JSON.stringify(errorLog)}`); + } else { + this.logger.warn(`Client error: ${JSON.stringify(errorLog)}`); + } + response.status(status).json({ success: false, code,