nest exception filters异常过滤器练习

异常过滤器

import { ArgumentsHost, Catch, ExceptionFilter } from "@nestjs/common"
import { formatDate } from "src/utils"

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
	catch(exception: HttpException, host: ArgumentsHost) {
		const ctx = host.switchToHttp()
		const response = ctx.getResponse()
		const request = ctx.getRequest()
		const status = 
			exception instanceof HttpException
				? exception.getStatus()
				: HttpStatus.INTERNAL_SERVER_ERROR

		const message = exception.message
		Logger.log(exception, "错误提示")
		const errorResponse = {
			status,
			message,
			code: 1, // 自定义code
			path: request.url,
			method: request.method,
			timestamp: new Date().tiISOString()
		}
		Logger.error(
			`【${formatDate(Date.now())}${request.method} ${request.url}`,
			JSON.stringify(errorReponse),
			"HttpExceptionFilter"
		)
		response.status(status)
		response.header("Content-Type", "application/json; chartset=utf-8")
		response.send(errorResponse)
	}
}

使用

@Post()
@UseFilters(new HttpExceptionFilter()) // HttpExceptionFilter 实例  类
async create(@Body() createCatDto: CreateCatDto) {
  throw new ForbiddenException();
}

@UseFilters(new HttpExceptionFilter())
export class CatsController {}

全局注入异常过滤器

import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';

@Module({
  providers: [
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
    },
  ],
})
export class AppModule {}

你可能感兴趣的:(nest)