Skip to content

异常过滤器

向军大叔每晚八点在 抖音bilibli 直播

xj-small

使用 filter 过滤器可以对异常进行自定义处理。

import { ArgumentsHost, BadRequestException, Catch, ExceptionFilter, HttpException } from '@nestjs/common'
import { Response } from 'express'

@Catch(HttpException)
export class ValidateExceptionFilter 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()
    //自定义异常处理
    if (exception instanceof BadRequestException) {
      // return response.json(exception.getResponse())
    }

    return response
      .status(status)
      .json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}