Nest.js Tutorial

Error handling and data validation

Marcin Wanago
JavaScriptNestJSTypeScript

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  BaseExceptionFilter. We can look into the source code of NestJS and inspect its behavior.

nest/packages/core/exceptions/base-exception-filter.ts
1export class BaseExceptionFilter<T = any> implements ExceptionFilter<T> {
2  // ...
3  catch(exception: T, host: ArgumentsHost) {
4    // ...
5    if (!(exception instanceof HttpException)) {
6      return this.handleUnknownError(exception, host, applicationRef);
7    }
8    const res = exception.getResponse();
9    const message = isObject(res)
10      ? res
11      : {
12          statusCode: exception.getStatus(),
13          message: res,
14        };
15    // ...
16  }
17 
18  public handleUnknownError(
19    exception: T,
20    host: ArgumentsHost,
21    applicationRef: AbstractHttpAdapter | HttpServer,
22  ) {
23    const body = {
24      statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
25      message: MESSAGES.UNKNOWN_EXCEPTION_MESSAGE,
26    };
27    // ...
28  }
29}

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

HttpException

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

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

1throw new HttpException('Post not found', HttpStatus.NOT_FOUND);

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

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

  • statusCode: contains the HTTP code that we’ve chosen
  • message: the description that we’ve provided
We can override the above behavior by providing an object as the first argument of the  HttpException 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  HttpException class.

posts/exception/postNotFund.exception.ts
1import { HttpException, HttpStatus } from '@nestjs/common';
2 
3class PostNotFoundException extends HttpException {
4  constructor(postId: number) {
5    super(`Post with id ${postId} not found`, HttpStatus.NOT_FOUND);
6  }
7}

Our custom  PostNotFoundException calls the constructor of the   HttpException. 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  HttpException. One of them is  NotFoundException. We can refactor the above code and use it.

We can find the full list of built-in HTTP exceptions in the documentation.
posts/exception/postNotFund.exception.ts
1import { NotFoundException } from '@nestjs/common';
2 
3class PostNotFoundException extends NotFoundException {
4  constructor(postId: number) {
5    super(`Post with id ${postId} not found`);
6  }
7}

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

Extending the BaseExceptionFilter

The default  BaseExceptionFilter 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.

utils/exceptionsLogger.filter.ts
1import { Catch, ArgumentsHost } from '@nestjs/common';
2import { BaseExceptionFilter } from '@nestjs/core';
3 
4@Catch()
5export class ExceptionsLoggerFilter extends BaseExceptionFilter {
6  catch(exception: unknown, host: ArgumentsHost) {
7    console.log('Exception thrown', exception);
8    super.catch(exception, host);
9  }
10}

The  @Catch() 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 app.useGlobalFilters.

main.ts
1import { HttpAdapterHost, NestFactory } from '@nestjs/core';
2import { AppModule } from './app.module';
3import * as cookieParser from 'cookie-parser';
4import { ExceptionsLoggerFilter } from './utils/exceptionsLogger.filter';
5 
6async function bootstrap() {
7  const app = await NestFactory.create(AppModule);
8 
9  const { httpAdapter } = app.get(HttpAdapterHost);
10  app.useGlobalFilters(new ExceptionsLoggerFilter(httpAdapter));
11 
12  app.use(cookieParser());
13  await app.listen(3000);
14}
15bootstrap();

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

1import { Module } from '@nestjs/common';
2import { ExceptionsLoggerFilter } from './utils/exceptionsLogger.filter';
3import { APP_FILTER } from '@nestjs/core';
4 
5@Module({
6  // ...
7  providers: [
8    {
9      provide: APP_FILTER,
10      useClass: ExceptionsLoggerFilter,
11    },
12  ],
13})
14export class AppModule {}

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

1@Get(':id')
2@UseFilters(ExceptionsLoggerFilter)
3getPostById(@Param('id') id: string) {
4  return this.postsService.getPostById(Number(id));
5}

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  ExceptionFilter interface. Let’s look into an example:

1import { ExceptionFilter, Catch, ArgumentsHost, NotFoundException } from '@nestjs/common';
2import { Request, Response } from 'express';
3 
4@Catch(NotFoundException)
5export class HttpExceptionFilter implements ExceptionFilter {
6  catch(exception: NotFoundException, host: ArgumentsHost) {
7    const context = host.switchToHttp();
8    const response = context.getResponse<Response>();
9    const request = context.getRequest<Request>();
10    const status = exception.getStatus();
11    const message = exception.getMessage();
12 
13    response
14      .status(status)
15      .json({
16        message,
17        statusCode: status,
18        time: new Date().toISOString(),
19      });
20  }
21}

There are a few notable things above. Since we use  @Catch(NotFoundException), this filter runs only for  NotFoundException.

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

Validation

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  ValidationPipe.

main.ts
1import { NestFactory } from '@nestjs/core';
2import { AppModule } from './app.module';
3import * as cookieParser from 'cookie-parser';
4import { ValidationPipe } from '@nestjs/common';
5 
6async function bootstrap() {
7  const app = await NestFactory.create(AppModule);
8  app.useGlobalPipes(new ValidationPipe());
9  app.use(cookieParser());
10  await app.listen(3000);
11}
12bootstrap();

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.

1npm install class-validator class-transformer
For the  ValidationPipe to work we also need the class-transformer library
auth/dto/register.dto.ts
1import { IsEmail, IsString, IsNotEmpty, MinLength } from 'class-validator';
2 
3export class RegisterDto {
4  @IsEmail()
5  email: string;
6 
7  @IsString()
8  @IsNotEmpty()
9  name: string;
10 
11  @IsString()
12  @IsNotEmpty()
13  @MinLength(7)
14  password: string;
15}
16 
17export default RegisterDto;

Thanks to the fact that we use the above  RegisterDto with the  @Body() decorator, the ValidationPipe now checks the data.

1@Post('register')
2async register(@Body() registrationData: RegisterDto) {
3  return this.authenticationService.register(registrationData);
4}

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.

utils/findOneParams.ts
1import { IsNumberString } from 'class-validator';
2 
3class FindOneParams {
4  @IsNumberString()
5  id: string;
6}
1@Get(':id')
2getPostById(@Param() { id }: FindOneParams) {
3  return this.postsService.getPostById(Number(id));
4}

Please note that we don’t use  @Param('id') anymore here. Instead, we destructure the whole params object.

If you use MongoDB instead of Postgres, the  @IsMongoId() 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  skipMissingProperties to our  ValidationPipe.

1app.useGlobalPipes(new ValidationPipe({ skipMissingProperties: true }))

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  IsOptional to all properties when updating data.

1import { IsString, IsNotEmpty, IsNumber, IsOptional } from 'class-validator';
2 
3export class UpdatePostDto {
4  @IsNumber()
5  @IsOptional()
6  id: number;
7 
8  @IsString()
9  @IsNotEmpty()
10  @IsOptional()
11  content: string;
12 
13  @IsString()
14  @IsNotEmpty()
15  @IsOptional()
16  title: string;
17}

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

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

Summary

In this article, we’ve looked into how error handling and validation works in NestJS. Thanks to looking into how the default  BaseExceptionFilter 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  ValidationPipe and the class-validator library to validate incoming data.

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