API with NestJS #4. Error handling and data validation

栏目: IT技术 · 发布时间: 3年前

内容简介: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

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<T> {
  // ...
  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

API with NestJS #4. Error handling and data validation

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.

API with NestJS #4. Error handling and data validation

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<Response>();
    const request = context.getRequest<Request>();
    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 theTypeScript 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 f irst 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);
}

API with NestJS #4. Error handling and data validation

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

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

import { IsString, IsNotEmpty, IsNumber, IsOptional } from 'class-validator';
 
export class UpdatePostDto {
  @IsNumber()
  @IsOptional()
  id: number;
 
  @IsString()
  @IsNotEmpty()
  @IsOptional()
  content: string;
 
  @IsString()
  @IsNotEmpty()
  @IsOptional()
  title: string;
}

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!


以上所述就是小编给大家介绍的《API with NestJS #4. Error handling and data validation》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

算法设计与分析基础

算法设计与分析基础

莱维丁 (Anany Levitin) / 清华大学出版社 / 2013-5-1 / CNY 79.00

《算法设计与分析基础(第3版 影印版)》在讲述算法设计技术时采用了新的分类方法,在讨论分析方法时条分缕析,形成了连贯有序、耳目一新的风格。为便于学生掌握,本书涵盖算法入门课程的全部内容,更注重对概念(而非形式)的理解。书中通过一些流行的谜题来激发学生的兴趣,帮助他们加强和提高解决算法问题的能力。每章小结、习题提示和详细解答,形成了非常鲜明的教学特色。 《算法设计与分析基础(第3版 影印版)》......一起来看看 《算法设计与分析基础》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具