簡體   English   中英

如何在 Nestjs 中使用 globalPipse 進行自定義響應

[英]How to make custom response using globalPipse in nestjs

我使用'class-validator'的dto在user.controller中寫了一個api。

  @Post('/')
  public async createUser(
    @Res() res,
    @Body() createUserDto: CreateUserDto,
  ) {
    ... do something
  }

我將 useGlobalPipes 放在 main.ts 中。

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
      forbidNonWhitelisted: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  );

當我向 api 提出請求時,我收到以下回復。

{
    "statusCode": 400,
    "message": [
        "userName should not be empty",
        "userName must be a string",
    ],
    "error": "Bad Request"
}

到目前為止,它與 nestjs 一起工作沒有問題。
但我想得到這樣的自定義響應。

{
    "code": 400,
    "errorReason": [
        "userName should not be empty",
        "userName must be a string",
    ],
    "msg": "Bad Request",
    "success": false
}

我可以獲得維護上述代碼的自定義響應嗎?
如果它可以做到,你能給我一些建議或一些代碼嗎?
感謝您閱讀我的問題。

在 Nest 中,管道非常適合驗證、轉換傳入的 object、在某些情況下可能與數據庫通信,並在出現任何問題時拋出錯誤。 如果要更改響應,則在引發錯誤后,您需要考慮使用ExceptionFilter在哪里可以執行類似的操作

@Catch()
export class CatchAllFilter implements ExceptionFilter {

  catch(exception: Error, host: ArgumentHost) {
    res
      .status((exception.getStatus && exception.getStatus()) || 500)
      .send({
        (exception.getResponse && ...exception.getResponse()) || ...{ message: exception.message },
        success: false
      });
  }
}

上面的代碼肯定會出現類型錯誤,但它應該會引導你走上正確的軌道

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM