zoukankan      html  css  js  c++  java
  • [NestJS] Fallback Exception Filter

    Fallback exception filter is mean to catch any exception which are not catched by other exception filters;

    import { Catch, ExceptionFilter, ArgumentsHost } from "@nestjs/common";
    
    @Catch()
    export class FallbackExpectionFilter implements ExceptionFilter {
        catch(exception: any, host: ArgumentsHost) {
            console.log('fallback exception handler triggered',
            JSON.stringify(exception));
    
            const ctx = host.switchToHttp();
            const response = ctx.getResponse();
    
            return response.status(500)
                .json({
                    statusCode: 500,
                    createdBy: "FallbackExceptionFilter",
                    errorMessage: exception.message ? exception.message: 'Unexpected error ocurred';
                });
        }
    }

    main.ts:

    import { NestFactory } from '@nestjs/core';
    
    import { AppModule } from './app.module';
    import { HttpExceptionFilter } from './filters/http-exception.filter';
    import { FallbackExpectionFilter } from './filters/fallback.filter';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
    
      app.setGlobalPrefix('api');
      app.useGlobalFilters(
        new FallbackExpectionFilter(),
        new HttpExceptionFilter(),
      );
    
      await app.listen(9000);
    }
    
    bootstrap();

    Order matters, from most generic to specific.

  • 相关阅读:
    ADO.Net——增、删、改、查
    面向对象——类库五大原则
    面向对象——设计模式和委托
    JS 函数 内置方法和对象
    js 字符串、数组类型 及方法
    复习一下 Python三元运算
    复习一下 列表
    前端 2 CSS 选择器
    前端 1 HTML
    39
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12196529.html
Copyright © 2011-2022 走看看