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 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.
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/ to a non-existing card:
http://localhost:3000/cards/list/1698691077473
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:
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
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:
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!
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.
Top comments (0)