首页 > 解决方案 > 抛出 HTTP 嵌套异常会导致 Promise 被拒绝

问题描述

我正在尝试抛出一个 http 嵌套异常以使用默认的嵌套处理程序。

我试图在调用 adminService.update 函数的控制器中抛出异常,并且非常成功。

  async update(update: DeepPartial<Admin>) {
    const admin = await this.findOne({ id: update.id});
    const adminName = await this.findOne({ username: update.username});
    if (!adminName) {
      throw new ConflictException('Username already in use');
    }
    admin.username = update.username;
    admin.save();
  }

将调用放入控制器时的输出:

{
  "statusCode": 409,
  "error": "Conflict",
  "message": "Username already in use"
}

控制器方法。

  @Put()
  async update(@Body() updateDTO: UpdateDTO): Promise<void> {
    throw new ConflictException('Username already in use');
    this.adminService.update(updateDTO);
  }

错误本身:

UnhandledPromiseRejectionWarning: Error: [object Object] at AdminService.<anonymous> (C:\Users\JBRETAS_EXT\Documents\mapa-digital\dist\admin\admin.service.js:55:19) at Generator.next (<anonymous>)

标签: node.jsnestjs

解决方案


似乎我的控制器方法中缺少 return 语句。

  @Put()
  async update(@Body() updateDTO: UpdateDTO): Promise<void> {
    return this.adminService.update(updateDTO);
  }

推荐阅读