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();
  • 相关阅读:
    nmap 快速扫描所有端口
    cdh ntpdate 问题
    看22是不是被玻璃破解
    lucas定理
    HDU1398--Square Coins(母函数)
    【转】HDU1028
    【转】母函数(Generating function)详解 — TankyWoo(红色字体为批注)
    HDU--1085--Holding Bin-Laden Captive!(母函数)
    HDU2588--GCD(欧拉函数)
    【转】扩展欧几里德
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12187126.html
Copyright © 2011-2022 走看看