NestJS ( 二 ) 拦截器

132 阅读1分钟

image.png 拦截器具有一系列有用的功能,这些功能受面向切面编程(AOP)技术的启发。它们可以:

  • 在函数执行之前/之后绑定额外的逻辑
  • 转换从函数返回的结果
  • 转换从函数抛出的异常
  • 扩展基本函数行为
  • 根据所选条件完全重写函数 (例如, 缓存目的)

响应映射

形成良好统一的格式返回无论对前端还是自查都是十分良好的

例如:

{
   data:{},
   status:200,
   message:"",
   success:true
}

全局拦截响应

 app.useGlobalInterceptors(new Response())
 import { Injectable, NestInterceptor, CallHandler } from '@nestjs/common'
 import { map } from 'rxjs/operators'
 import {Observable} from 'rxjs'
  
 interface data<T>{
     data:T
 }

 @Injectable()
 export class Response<T = any> implements NestInterceptor {
     intercept(_context, next: CallHandler):Observable<data<T>> {
         return next.handle().pipe(map(data => {
             return {
                status:200,
                data,
                success:true,
                message:"成功"
             }
         }))
     }
 }

image.png

异常映射

在NestJS中,我们可以使用异常映射机制来处理不同类型的错误并返回友好的错误响应。异常是在应用程序中发生的运行时错误,可能需要针对不同的异常类型采取不同的措施。

  app.useGlobalFilters(new CustomCatchErrorExceptionFilter())
import { ArgumentsHost, Catch, ExceptionFilter, HttpStatus } from '@nestjs/common';
import { Response } from 'express';

@Catch()
export class CustomCatchErrorExceptionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
 const ctx = host.switchToHttp();
 const response = ctx.getResponse<Response>();
 console.log("exception", exception.response)
 const message = exception.message;
 response.status(HttpStatus.BAD_REQUEST).json({
   message,
   status: (exception.response && exception.response.statusCode) || HttpStatus.BAD_REQUEST,
   path: ctx.getRequest().url,
   timestamp: new Date().toISOString(),
 });
}
}

image.png