在 nest js 中正确实现 try-catch 关于异常

Proper implementation of try-catch in nest js regarding exceptions

提问人:sl_89 提问时间:11/6/2023 最后编辑:sl_89 更新时间:11/6/2023 访问量:31

问:

我想在try-catch构造中实现通过其id从数据库中获取项目的服务逻辑。如果具有此类 id 的项目不存在,那么我想抛出 404,否则如果我有一些服务器错误/意外行为 - 500。我的服务实现如下:

  async fetchItem(id: string): Promise<Item> {
    try {
      const item = await this.ItemsRepository.findOneBy({ id });
      if (!item)
        throw new HttpException("Item wasn't found", HttpStatus.NOT_FOUND); // here I want to stop function execution
      return item;
    } catch (err) {
      throw new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

问题是如果该项目不存在,我会得到 500 状态代码。

据我了解,如果我在块中抛出错误,那么我会自动去块。我考虑过将 404 异常移动到阻止,但我认为这不是一个好主意,因为我可能遇到服务器问题并且状态不合适。我应该如何实现这一点?trycatchcatch

JavaScript 错误处理 nestjs

评论


答:

1赞 Bergi 11/6/2023 #1

async fetchItem(id: string): Promise<Item> {
  const item = await this.ItemsRepository.findOneBy({ id }).catch(err => {
    throw new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR);
  });
  if (!item) {
    throw new HttpException("Item wasn't found", HttpStatus.NOT_FOUND);
  }
  return item;
}

对 / 做同样的事情是可能的,但很丑陋trycatch