Managing HTTP Errors in NestJS Effortlessly
Published: 2024-01-08 15:53:32

---
title: Managing HTTP Errors in NestJS Effortlessly
published: true
date: 2023-10-30 19:49:16 UTC
tags: 
canonical_url: https://www.danywalls.com/managing-http-errors-in-nestjs-effortlessly
---

When we develop applications, errors can also occur in the API, such as when we request data and it doesn't exist or the database is unavailable. How can we catch and handle errors in the API?

For instance, in the [Jumbo API](https://github.com/danywalls/jumbo_project), we the `cards.service` find and update methods. What happens if the ID is non-existent or the card update is unsuccessful?

Don't worry, Nest offers an easy way to handle errors and send back user-friendly error messages to the client! Let's do it!

> This article is part of [my series about NestJS](https://www.danywalls.com/series/nestjs).

## Handle Exception with HTTP Exception

Open the API, with the command `npm run start:dev`, with the browser, navigate to a non exist card in the endpoint [http://localhost:3000/cards/list/](http://localhost:3000/cards/list/1698691077473) to a non-existing card:

[http://localhost:3000/cards/list/1698691077473](http://localhost:3000/cards/list/1698691077473)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1698692426236/f32cc082-702d-45e8-bc44-d696ddcae0c1.png)

The API returns empty, we don't know what is happening. the best approach is to notify to the consumer the card request doesn't exist.

The easy way is to fix it using the HttpException, which allows us to send an error message combined with the response status.

Let's do it! First, check if the card is `null` before returning the value. If it is `null`, use the HttpException class to throw an error. The `HttpException` expects a message and a status code.

The final code looks like this:

```
getById(id: string): Card { const card = this.cards.find((card) => card.id === +id); if (!card) { throw new HttpException( `Sorry, card ${id} was not found`, HttpStatus.NOT_FOUND, ); } return card; }
```

Save the changes and try again to retrieve the same card ID:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1698692792283/29abd22c-db92-4536-a178-e8b5fb3b70cf.png)

Yes! We received a clear message that the card doesn't exist!

## Using Build-in HTTP Exceptions

Nest provides a set of the most common HTTP exceptions, making it easier for us to handle exceptions such as `BadRequestException`, `UnauthorizedException`, `NotFoundException`, `ForbiddenException`, and more.

> Read the list of [Build-in HttpException](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)

Let's update our code to a simpler version using the built-in HTTP exceptions, and change the HttpException to NotFoundException. It only requires the message, and NestJS takes care of the rest for us.

```
  getById(id: string): Card { const card = this.cards.find((card) => card.id === +id); if (!card) { throw new NotFoundException(`Sorry, card ${id} was not found`); } return card; }
```

Save the changes and try again:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1698693514504/11c960bb-db66-4de3-9815-521fdc937ac8.png)

We keep the error control with less code!

What happens if I forget some handle some error that breaks an application like an external library that throws the error?

Nest catches the error using the exception layer and sends a specific error to the consumer for us. Let's try to force an error, try again, and it will send an error message with a status code.

```
  getById(id: string): Card { const card = this.cards.find((card) => card.id === +id); throw Error('Ups something fail'); }
```

Save changes again and try!

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1698693617621/b5669a42-01e9-4fc7-b300-5ac5e32b02e7.png)

Yes, we received a user-friendly message and a clear error for the consumers!

## Recap

We learned to manage errors in API with NestJS. We discovered using `HttpException` class for easy-to-understand error messages and how Nest has `built-in` exceptions for usual errors. We also learned how Nest catches unexpected errors with the exception layer, giving clear messages and status codes for API users.

If you want to learn more feel free to check out [the official documentation](https://docs.nestjs.com/exception-filters#built-in-http-exceptions).