Search⌘ K
AI Features

Custom Exception

Explore how to implement NestJS built-in exceptions and create custom exceptions tailored to your application's needs. Understand extending HttpException to add properties like errorHash and timestamp for better error tracking and debugging. This lesson helps you build more robust and maintainable APIs through effective exception handling.

NestJS provides a set of built-in exceptions. These exceptions cover standard HTTP status codes, such as “404 Not Found,” “500 Internal Server Error,” etc. Sometimes, we might also need to create a custom exception for the specific needs of our application.

In this lesson, we’ll explore the built-in exceptions and learn how to implement custom exceptions to manage exceptions effectively.

The HttpException exception and other built-in exceptions

In the previous lesson, we used the built-in HttpException. The HttpException exception is handled by default in NestJS. If HttpException is thrown, it will be mapped to the appropriate HTTP response and returned to the client.

A HttpException exception takes two parameters: response message and status code. We can throw an exception using the following code:

throw new HttpException('Address creation failed', HttpStatus.INTERNAL_SERVER_ERROR);
Throwing HttpException

NestJS offers a range of built-in exceptions inherited from the HttpException class. These exceptions cover various scenarios and simplify error handling. Here are some of the ...