• [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();
  • 相关阅读:
    任务08——第一次半月学习总结
    任务5
    任务4
    任务3
    任务2
    mission 01
    HTML-CSS-JS Prettify报错Node.js was not found
    **1279
    UVa 10735
    UVa 1515
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12187126.html
Copyright © 2020-2023  润新知