500: not-uuid 类型而不是 404

500: not-uuid type instead of 404

(我是这方面的新手) 我正在为我的应用程序使用 nestjs+typeorm+postgres。数据库中有一个“社区”列,它使用 UUID 类型作为 id。 所以在我的应用程序中,我编写了一个基本逻辑来从给定的查询 ID 和 returns 404 中找出确切的社区,如果没有找到,但是如果我在我的请求中发送非 UUID 类型 URL ,它抛出 500 说非 UUID 类型并且应用程序崩溃。 为什么我没有得到正确的 404? 我确实尝试并抓住了避免应用程序崩溃的方法,但应该有一种方法可以 return 正确的 404。

我的Community.service.ts文件(需要的部分):

// GET: gets the specified community if id provided in
  // query, otherwise returns all communities
  public async getCommunity(id?: string): Promise<Community | Community[]> {
    if (!id) {
      const communities = await this.communityRepository.find();
      return communities;
    } else {
      const community = this.communityRepository.findOne(id);
      return community;
    }
  } 

这里是 community.controller.ts(需要的部分):

@Get('')
  async getAllCommunities(
    @Query('id') id?: string,
  ): Promise<Community[] | Community> {
    try {
      const communities = await this.communityService.getCommunity(id);
      if (!communities) {
        throw new NotFoundException();
      }
      return communities;
    } catch (err) {
      return err;
    }
  }

如果定义了 id,我建议您安装 class-validator 并使用 isUUID(id) 验证器。 这样做你可以检查 id 是否是一个有效的 UUID,如果不是则抛出错误。

示例:

@Get('')
async getAllCommunities(
  @Query('id') id?: string,
): Promise<Community[] | Community> {
  // If 'id' is defined check if it's a valid UUID format
  if(id && !isUUID(id)) throw new Error(`Invalid id, UUID format expected but received ${id}`);

  try {
    const communities = await this.communityService.getCommunity(id);
    if (!communities) throw new NotFoundException();
    return communities;
  } catch (error) {
    return error;
  }
}