---
title: "Managing HTTP Errors in NestJS Effortlessly"
date: "2023-10-30"
slug: "managing-http-errors-in-nestjs-effortlessly"
author: "Dany Paredes"
canonical: "https://danywalls.com/managing-http-errors-in-nestjs-effortlessly"
description: "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, we the cards.service find..."
---

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)

![](/images/posts/managing-http-errors-in-nestjs-effortlessly/f32cc082-702d-4_91082.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:

```typescript
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:

![](/images/posts/managing-http-errors-in-nestjs-effortlessly/29abd22c-db92-4_91083.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.

```typescript
  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:

![](/images/posts/managing-http-errors-in-nestjs-effortlessly/11c960bb-db66-4_91083.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.

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

Save changes again and try!

![](/images/posts/managing-http-errors-in-nestjs-effortlessly/b5669a42-01e9-4_91083.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).
