Search code examples
javascripterror-handlingnestjs

Proper implementation of try-catch in nest js regarding exceptions


I want to implement service logic of fetching an item by its id from a database in try-catch construction. If an item with such id doesn't exist, then I want to throw 404, else if I have some server error/unexpected behavior - 500. My service implementation is as the following:

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

The problem is if the item doesn't exist, I get 500 status code.

As far as I understood, if I throw an error in try block, then I automatically go to catch block. I thought about moving 404 exception to catch block but I don't think it's a good idea as I might have server problem and the status won't be suitable. How should I implement this?


Solution

  • Use

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

    Doing the same with try/catch is possible but ugly.