Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading