如何配置NestJS在遇到异常后继续运行?

问题描述 投票:0回答:1

我正在使用 NestJS 10。我使用

在本地启动我的服务器
npm run start:dev

在我的 package.json 中定义为

"start:dev": "nest start --watch",

存在一个问题,如果控制器方法抛出异常,服务器将无法响应任何其他请求。例如,我有这个控制器方法...

@Controller(ORDERS_CONTEXT_PATH)
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  @UseGuards(OptionalAccessTokenGuard)
  @Post('paymentIntent')
  createPaymentIntent(
    @Req() req: Request,
    @Body() createOrderItemDtos: CreateOrderItemDto[],
  ): Promise<PaymentIntent> {
    const userId = req.user ? req.user['sub'] : null;
    return this.ordersService.createPaymentIntent(userId, createOrderItemDtos);
  }

如果底层服务抛出异常,NestJS 控制台会报告...

/Users/myuser/Documents/workspace/myproject/src/orders/orders.service.ts:43
      createOrderDto.orderItems.map(async (orderItemDto) => {
                                ^
TypeError: Cannot set properties of undefined (setting 'id')
    at /Users/myuser/Documents/workspace/myproject/src/orders/orders.service.ts:47:18
    at Array.map (<anonymous>)
    at OrdersService.create (/Users/myuser/Documents/workspace/myproject/src/orders/orders.service.ts:43:33)
    at runOriginal (/Users/myuser/Documents/workspace/myproject/node_modules/typeorm-transactional/src/transactions/wrap-in-transaction.ts:53:34)
    at OrdersService.<anonymous> (/Users/myuser/Documents/workspace/myproject/node_modules/typeorm-transactional/src/transactions/wrap-in-transaction.ts:117:20)
    at step (/Users/myuser/Documents/workspace/myproject/node_modules/typeorm-transactional/dist/transactions/wrap-in-transaction.js:33:23)
    at Object.next (/Users/myuser/Documents/workspace/myproject/node_modules/typeorm-transactional/dist/transactions/wrap-in-transaction.js:14:53)
    at /Users/myuser/Documents/workspace/myproject/node_modules/typeorm-transactional/dist/transactions/wrap-in-transaction.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (/Users/myuser/Documents/workspace/myproject/node_modules/typeorm-transactional/dist/transactions/wrap-in-transaction.js:4:12)

但现在每当我提出其他请求(甚至向不同的控制器)时,我都会反复得到

Error: connect ECONNREFUSED 127.0.0.1:3000

从服务器返回。如果存在潜在问题,是否有一种通用方法可以将我的服务器配置为返回 500 并允许它继续处理客户端请求?

exception configuration nestjs internal-server-error
1个回答
0
投票

问题是在处理请求的过程中出现异常,服务器可能会进入失败状态,使得后续的请求也失败。

此问题的一个解决方案是向您的 NestJS 应用程序添加一个 全局异常过滤器。该过滤器将捕获任何未处理的异常并以适当的错误状态代码进行响应,从而允许服务器继续处理其他请求。您可以通过实现 ExceptionFilter 接口来创建全局异常过滤器。

示例

import { Catch, ArgumentsHost, HttpStatus } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';

@Catch()
export class GlobalExceptionFilter extends BaseExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const status = exception instanceof Error ? HttpStatus.INTERNAL_SERVER_ERROR : HttpStatus.BAD_REQUEST;

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}

然后,您需要将此过滤器应用到您的应用程序中。您可以在主应用程序模块(例如 app.module.ts)中执行此操作:

import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { GlobalExceptionFilter } from './path-to-global-exception-filter';

@Module({
  ...
  providers: [
    {
      provide: APP_FILTER,
      useClass: GlobalExceptionFilter,
    },
  ],
})
export class AppModule {}
© www.soinside.com 2019 - 2024. All rights reserved.