API with NestJS #4. Error handling and data validation

JavaScript NestJS TypeScript

This entry is part 4 of 158 in the API with NestJS

NestJS shines when it comes to handling errors and validating data. A lot of that is thanks to using decorators. In this article, we go through features that NestJS provides us with, such as Exception filters and Validation pipes.

The code from this series results in this repository. It aims to be an extended version of the official Nest framework TypeScript starter.

Exception filters

Nest has an exception filter that takes care of handling the errors in our application. Whenever we don’t handle an exception ourselves, the exception filter does it for us. It processes the exception and sends it in the response in a user-friendly format.

The default exception filter is called  . We can look into the source code of NestJS and inspect its behavior.


Every time there is an error in our application, the   method runs. There are a few essential things we can get from the above code.


Nest expects us to use the  class. If we don’t, it interprets the error as unintentional and responds with 500 Internal Server Error.

We’ve used  quite a bit in the previous parts of this series:

The constructor takes two required arguments: the response body, and the status code. For the latter, we can use the provided   enum.

If we provide a string as the definition of the response, NestJS serialized it into an object containing two properties:

  • : contains the HTTP code that we’ve chosen
  • : the description that we’ve provided

We can override the above behavior by providing an object as the first argument of the   constructor.

We can often find ourselves throwing similar exceptions more than once. To avoid code duplication, we can create custom exceptions. To do so, we need to extend the   class.


Our custom   calls the constructor of the   . Therefore, we can clean up our code by not having to define the message every time we want to throw an error.

NestJS has a set of exceptions that extend the  . One of them is  . We can refactor the above code and use it.

We can find the full list of built-in HTTP exceptions in the documentation.


The first argument of the   class is an additional   property. This way, our   is defined by   and is based on the status.

Extending the BaseExceptionFilter

The default   can handle most of the regular cases. However, we might want to modify it in some way. The easiest way to do so is to create a filter that extends it.


The   decorator means that we want our filter to catch all exceptions. We can provide it with a single exception type or a list.

The ArgumentsHost hives us access to the execution context of the application. We explore it in the upcoming parts of this series.

We can use our new filter in three ways. The first one is to use it globally in all our routes through .


A better way to inject our filter globally is to add it to our . Thanks to that, we could inject additional dependencies into our filter.

The third way to bind filters is to attach the   decorator. We can provide it with a single filter, or a list of them.

The above is not the best approach to logging exceptions. NestJS has a built-in Logger that we cover in the upcoming parts of this series.

Implementing the ExceptionFilter interface

If we need a fully customized behavior for errors, we can build our filter from scratch. It needs to implement the   interface. Let’s look into an example:

There are a few notable things above. Since we use  , this filter runs only for  .

The   method returns the   object with information about the HTTP context. We explore it a lot in the upcoming parts of this series when discussing the execution context.


We definitely should validate the upcoming data. In the TypeScript Express series, we use the class-validator library. NestJS also incorporates it.

NestJS comes with a set of built-in pipes. Pipes are usually used to either transform the input data or validate it. Today we only use the predefined pipes, but in the upcoming parts of this series, we might look into creating custom ones.

To start validating data, we need the  .


In the first part of this series, we’ve created Data Transfer Objects. They define the format of the data sent in a request. They are a perfect place to attach validation.

For the  to work we also need the class-transformer library


Thanks to the fact that we use the above   with the   decorator, the  now checks the data.

There are a lot more decorators that we can use. For a full list, check out the class-validator documentation. You can also create custom validation decorators.

Validating params

We can also use the class-validator library to validate params.


Please note that we don’t use   anymore here. Instead, we destructure the whole params object.

If you use MongoDB instead of Postgres, the   decorator might prove to be useful for you here

Handling PATCH

In the TypeScript Express series, we discuss the difference between the PUT and PATCH methods. Summing it up, PUT replaces an entity, while PATCH applies a partial modification. When performing partial changes, we need to skip missing properties.

The most straightforward way to handle PATCH is to pass   to our  .

Unfortunately, this would skip missing properties in all of our DTOs. We don’t want to do that when posting data. Instead, we could add   to all properties when updating data.

Unfortunately, the above solution is not very clean. There are some solutions provided to override the default behavior of the  here.

In the upcoming parts of this series we look into how we can implement PUT instead of PATCH


In this article, we’ve looked into how error handling and validation works in NestJS. Thanks to looking into how the default   works under the hood, we now know how to handle various exceptions properly. We know also know how to change the default behavior if there is such a need. We’ve also how to use the   and the class-validator library to validate incoming data.

There is still a lot to cover in the NestJS framework, so stay tuned!

Series Navigation<< API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookiesAPI with NestJS #5. Serializing the response with interceptors >>
Notify of
Newest Most Voted
Inline Feedbacks
View all comments
3 years ago

Hi, l I want to thank you for this amazing blog. Haven’t had that much learning something new in a long time.

3 years ago

Hi, Thank you ffor this great tutorial, but I have a problem everytime i try to login i get the 401 unauthorized response. any help please?

3 years ago
Reply to  Achref

You have to log in, using the API /authorization/log-in. But before that, you must also have an account registered using the API /authorization/register

1 year ago

Thank you very much about the article, but i have a question
How can i pass a list of classes error, currently it can only hande one error class because we use   @Catch(NotFoundException)

1 year ago
Reply to  hieple

Only ommit NotFoundException


1 year ago

Thanks for your quality articles.

I think you should talk about a very important attribute for the ValidationPipe: whitelist.

It is totally unintuitive that is default to false and very dangerous not to put it to true. It is possible to modify any element of the entity (for example, a createdAt)

7 months ago

I see that we have folders like : serviceS, interfaceS, should we use exceptionS instead of exception ? basic question right here