zoukankan      html  css  js  c++  java
  • [NestJs] Introduction to NestJs Error Handling & Expection filter

    Throw expection from Controller:

      @Put(':courseId')
      async updateCourse(
        @Param('courseId') courseId: string,
        @Body() changes: Partial<Course>,
      ): Promise<Course> {
        if (changes._id) {
          throw new BadRequestException('Cannot update course id');
        }
    
        return this.couresDB.updateCourse(courseId, changes);
      }

    Expection types: https://docs.nestjs.com/exception-filters#built-in-http-exceptions

    We can create global reuseable expection filters:

    src/filters/http-expections.filter.ts:

    import {
      ExceptionFilter,
      Catch,
      ArgumentsHost,
      HttpException,
    } from '@nestjs/common';
    import { Request, Response } from 'express';
    
    @Catch(HttpException)
    export class HttpExceptionFilter implements ExceptionFilter {
      catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const request = ctx.getRequest<Request>();
        const status = exception.getStatus();
    
        response.status(status).json({
          statusCode: status,
          timestamp: new Date().toISOString(),
          path: request.url,
          createdBy: 'HttpExceptionFilter',
          errorMessage: exception.message.message,
        });
      }
    }

    Using it for one single HTTP request:

      @Put(':courseId')
      @UseFilters(new HttpExceptionFilter())
      async updateCourse(
        @Param('courseId') courseId: string,
        @Body() changes: Partial<Course>,
      ): Promise<Course> {
        if (changes._id) {
          throw new BadRequestException('Cannot update course id');
        }
    
        return this.couresDB.updateCourse(courseId, changes);
      }

    Using it for one controller's all HTTP Requests:

    @Controller('courses')
    @UseFilters(new HttpExceptionFilter())
    export class CoursesController {

    Using it for all global requests:

    main.ts:

    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.setGlobalPrefix('api');
      app.useGlobalFilters(new HttpExceptionFilter());
    
      await app.listen(9000);
    }
    
    bootstrap();
  • 相关阅读:
    【关系抽取-mre-in-one-pass】加载数据(一)
    google colab上如何下载bert相关模型
    【关系抽取-R-BERT】定义训练和验证循环
    【关系抽取-R-BERT】模型结构
    【关系抽取-R-BERT】加载数据集
    【python刷题】关于一个序列的入栈出栈有多少种方式相关
    【python刷题】二维数组的旋转
    transformer相关变体
    数据结构与算法:树
    数据结构与算法:哈希表
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12187126.html
Copyright © 2011-2022 走看看