[NestJS] exception & filter

abnormal

base exception class

In NestJS HttpExceptionis the base exception class.

We can new HttpException(响应体, HTTP 状态码)create and throw it.

The here HTTP 状态码can be HttpStatusobtained from the NestJS built-in enumeration.

@Get()
findAll() {
    
    
    throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
}

Now when the client calls this routing function, the response looks like this:

{
    
    
    "statusCode": 403,
    "message": "Forbidden"
}

Built-in HTTP exceptions

NestJS has a built-in set HttpExceptionof :

  1. BadRequestException
  2. UnauthorizedException
  3. NotFoundException
  4. ForbiddenException
  5. NotAcceptableException
  6. RequestTimeoutException
  7. ConflictException
  8. GoneException
  9. PayloadTooLargeException
  10. UnsupportedMediaTypeException
  11. UnprocessableException
  12. InternalServerErrorException
  13. NotImplementedException
  14. BadGatewayException
  15. ServiceUnavailableException
  16. GatewayTimeoutException



exception filter

Exception filters can catch exceptions and return friendly response content to the front end.

NestJS has a built in global filter that handles HttpException(and its subclasses) exceptions. When the exception is not recognized (except for HttpException(and its subclasses of) exceptions), the user will receive the following JSON response:

{
    
    
    "statusCode": 500,
    "message": "Internal server error"
}

create filter

You can use the Nest-Cli command nest g filter XXX/ nest g f XXXto create a filter base frame.

import {
    
    
    ArgumentsHost,
    Catch,
    ExceptionFilter,
    HttpException,
} from '@nestjs/common';
import {
    
     Request, Response } from 'express';

@Catch(HttpException) // 捕获 HttpException 错误;  如果 @Catch() 里面没有参数, 则捕获所有错误
export class HttpExceptionFilter implements ExceptionFilter {
    
    
    catch(exception: HttpException, host: ArgumentsHost) {
    
    
        const ctx = host.switchToHttp(); // 获取上下文
        const status = exception.getStatus(); // 获取状态码

        // 通过上下文获取请求和响应
        const request = ctx.getRequest<Request>();
        const response = ctx.getResponse<Response>();

        // 自定义响应
        response.status(status).json({
    
    
            status,
            method: request.method,
            path: request.url,
            data: exception.message || exception.name,
            time: new Date().toLocaleString(),
        });
    }
}

@Catch(XXX)In the above example , XXXit is the exception that needs to be caught by the filter. If not written, it means to catch all exceptions. @Catch()Multiple parameters can be passed, and the parameters are ,separated .


register filter

There are [global], [controller], [routing] filters in NestJS

Global filter

app.useGlobalFilters()Register with ; there can only be one global filter

import {
    
     NestFactory } from '@nestjs/core';
import {
    
     AppModule } from './app.module';
import {
    
     HttpExceptionFilter } from './filters/http-exception.filter';

async function bootstrap() {
    
    
    const app = await NestFactory.create(AppModule);
    app.useGlobalFilters(new HttpExceptionFilter()); // 注册 Global 过滤器
    await app.listen(3000);
}
bootstrap();

Controller filter

@UseFilters()Register with ; ,separate multiple filters with

@Controller('project')
@UseFilters(new HttpExceptionFilter()) // 注册 Controller 过滤器
export class ProjectController {
    
    }

Route filter

@UseFiltersRegister with ; ,separate multiple filters with

@Post()
@UseFilters(new HttpExceptionFilter()) // 注册 Route 过滤器
create(@Body() createCatDto: CreateCatDto) {
    
    }

Use of filters

Because Nest makes it easy to reuse instances of the same class throughout a module, registering filters directly with the class instead of the instance can reduce memory overhead.

@Post()
@UseFilters(HttpExceptionFilter) // 直接使用类进行注册
create(@Body() createCatDto: CreateCatDto) {
    
    }

Guess you like

Origin blog.csdn.net/Superman_H/article/details/130030824