Search code examples
typescriptpostgresqlbackendnestjstypeorm

500: not-uuid type instead of 404


(I'm a newbie in this) I'm using nestjs+typeorm+postgres for my app. There is a "community" column in the db, which uses UUID type as id. So in my app, I have written a basic logic to find out the exact community from the given query ID and returns 404 if not found, but if I send non-UUID type in my request URL, it's throwing 500 saying non-UUID type and the app is crashing. Why I'm not getting proper 404? I did try and catch to avoid the app crashing but there should be a way to return proper 404.

My Community.service.ts file (needed part):

// 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;
    }
  } 

and here's community.controller.ts (needed part):

@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;
    }
  }

Solution

  • I suggest you to install class-validator and use the isUUID(id) validator if the id is defined. Doing this you can check that the id is a valid UUID, if not throw an error.

    Example:

    @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;
      }
    }