【问题标题】:500: not-uuid type instead of 404500:非 uuid 类型而不是 404
【发布时间】:2021-10-05 19:29:43
【问题描述】:

(我是这方面的新手) 我正在为我的应用程序使用nestjs+typeorm+postgres。 db中有一个“community”列,它使用UUID类型作为id。 所以在我的应用程序中,我编写了一个基本逻辑来从给定的查询 ID 中找出确切的社区,如果找不到则返回 404,但是如果我在请求 URL 中发送非 UUID 类型,它会抛出 500 说非 UUID 类型并且应用程序崩溃了。 为什么我没有得到正确的 404? 我确实尝试过避免应用程序崩溃,但应该有办法返回正确的 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;
    }
  }

【问题讨论】:

  • 首先,您从this.communityRepository.findOne(id); 中缺少await。如果id 不是undefined,我建议你安装class-validator 并使用isUUID() 验证器。这样做你可以检查 id 是否是一个有效的 UUID,如果没有抛出错误。
  • 感谢 CarloCorradini 我已经安装了类验证器,但不知道 UUID 检查
  • 很好,将其添加到答案中?

标签: typescript postgresql backend nestjs typeorm


【解决方案1】:

如果定义了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;
  }
}

【讨论】:

    猜你喜欢
    • 2011-07-07
    • 2015-05-26
    • 1970-01-01
    • 2020-07-06
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2023-03-15
    相关资源
    最近更新 更多