如何配置NestJS 10使服务器遇异常后仍可继续处理请求?
解决NestJS异常导致服务崩溃的问题
1. 配置全局异常过滤器
NestJS默认异常过滤器仅处理标准HTTP异常,未捕获的非HTTP异常(如服务层抛出的普通Error)可能导致进程崩溃。你可以自定义全局异常过滤器,统一捕获所有异常并返回500状态码,同时保证服务持续运行:
// src/common/filters/global-exception.filter.ts import { ExceptionFilter, Catch, ArgumentsHost, HttpStatus } from '@nestjs/common'; import { HttpAdapterHost } from '@nestjs/core'; @Catch() export class GlobalExceptionFilter implements ExceptionFilter { constructor(private readonly httpAdapterHost: HttpAdapterHost) {} catch(exception: unknown, host: ArgumentsHost): void { const { httpAdapter } = this.httpAdapterHost; const ctx = host.switchToHttp(); const responseBody = { statusCode: HttpStatus.INTERNAL_SERVER_ERROR, timestamp: new Date().toISOString(), path: httpAdapter.getRequestUrl(ctx.getRequest()), message: '服务器内部错误', }; httpAdapter.reply(ctx.getResponse(), responseBody, HttpStatus.INTERNAL_SERVER_ERROR); } }
在main.ts中注册该全局过滤器:
// src/main.ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { GlobalExceptionFilter } from './common/filters/global-exception.filter'; import { HttpAdapterHost } from '@nestjs/core'; async function bootstrap() { const app = await NestFactory.create(AppModule); const httpAdapterHost = app.get(HttpAdapterHost); app.useGlobalFilters(new GlobalExceptionFilter(httpAdapterHost)); await app.listen(3000); } bootstrap();
2. 拦截未捕获的Promise拒绝
如果服务层异步方法中存在未处理的Promise拒绝,可能导致Node.js进程直接退出。在main.ts中添加全局监听逻辑:
// src/main.ts,bootstrap函数外添加 process.on('unhandledRejection', (reason, promise) => { console.error('未处理的Promise拒绝:', reason); // 可在此添加日志上报等逻辑,避免进程退出 });
3. 规范服务层异常抛出
在服务层明确抛出NestJS标准异常,能让过滤器更精准处理:
// orders.service.ts import { InternalServerErrorException } from '@nestjs/common'; async createPaymentIntent(userId: string | null, items: CreateOrderItemDto[]) { try { // 业务逻辑代码 throw new Error('支付处理失败'); } catch (error) { throw new InternalServerErrorException(error.message); } }
验证效果
配置完成后,触发异常请求时,控制台会打印错误日志但服务不会退出,异常请求会收到500 Internal Server Error的JSON响应,后续请求仍能正常处理。
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

