7 min read
Original source

Error handling and data validation

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 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 export class BaseExceptionFilter<T = any> implements ExceptionFilter { // ... catch(exception: T, host: ArgumentsHost) { // ... if (!(exception instanceof HttpException)) { return this.handleUnknownError(exception, host, applicationRef); } const res = exception.getResponse(); const message = isObject(res) ? res : { statusCode: exception.getStatus(), message: res, }; // ... } public handleUnknownError( exception: T, host: ArgumentsHost, applicationRef: AbstractHttpAdapter | HttpServer, ) { const body = { statusCode: HttpStatus.INTERNAL_SERVER_ERROR, message: MESSAGES.UNKNOWN_EXCEPTION_MESSAGE, }; // ... } }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:throw 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 import { HttpException, HttpStatus } from '@nestjs/common'; class PostNotFoundException extends HttpException { constructor(postId: number) { super(`Post with id ${postId} not found`, HttpStatus.NOT_FOUND); } }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 import { NotFoundException } from '@nestjs/common'; class PostNotFoundException extends NotFoundException { constructor(postId: number) { super(`Post with id ${postId} not found`); } }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 import { Catch, ArgumentsHost } from '@nestjs/common'; import { BaseExceptionFilter } from '@nestjs/core'; @Catch() export class ExceptionsLoggerFilter extends BaseExceptionFilter { catch(exception: unknown, host: ArgumentsHost) { console.log('Exception thrown', exception); super.catch(exception, host); } }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 import { HttpAdapterHost, NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import * as cookieParser from 'cookie-parser'; import { ExceptionsLoggerFilter } from './utils/exceptionsLogger.filter'; async function bootstrap() { const app = await NestFactory.create(AppModule); const { httpAdapter } = app.get(HttpAdapterHost); app.useGlobalFilters(new ExceptionsLoggerFilter(httpAdapter)); app.use(cookieParser()); await app.listen(3000); } bootstrap();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.import { Module } from '@nestjs/common'; import { ExceptionsLoggerFilter } from './utils/exceptionsLogger.filter'; import { APP_FILTER } from '@nestjs/core'; @Module({ // ... providers: [ { provide: APP_FILTER, useClass: ExceptionsLoggerFilter, }, ], }) export 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.@Get(':id') @UseFilters(ExceptionsLoggerFilter) getPostById(@Param('id') id: string) { return this.postsService.getPostById(Number(id)); }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:import { ExceptionFilter, Catch, ArgumentsHost, NotFoundException } from '@nestjs/common'; import { Request, Response } from 'express'; @Catch(NotFoundException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: NotFoundException, host: ArgumentsHost) { const context = host.switchToHttp(); const response = context.getResponse(); const request = context.getRequest(); const status = exception.getStatus(); const message = exception.getMessage(); response .status(status) .json({ message, statusCode: status, time: new Date().toISOString(), }); } }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 import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import * as cookieParser from 'cookie-parser'; import { ValidationPipe } from '@nestjs/common'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe()); app.use(cookieParser()); await app.listen(3000); } bootstrap();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.npm install class-validator class-transformer For the  ValidationPipe to work we also need the class-transformer library auth/dto/register.dto.ts import { IsEmail, IsString, IsNotEmpty, MinLength } from 'class-validator'; export class RegisterDto { @IsEmail() email: string; @IsString() @IsNotEmpty() name: string; @IsString() @IsNotEmpty() @MinLength(7) password: string; } export default RegisterDto;Thanks to the fact that we use the above  RegisterDto with the  @Body() decorator, the ValidationPipe now checks the data.@Post('register') async register(@Body() registrationData: RegisterDto) { return this.authenticationService.register(registrationData); } 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 import { IsNumberString } from 'class-validator'; class FindOneParams { @IsNumberString() id: string; }@Get(':id') getPostById(@Param() { id }: FindOneParams) { return this.postsService.getPostById(Number(id)); }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, whil

Error handling and data validation | NestJS.io