# 异常过滤器
- 概述:Nest内置了一个异常处理器,负责处理应用程序中的所有未处理异常
- 使用cli生成异常处理器
nest g f error_name --no-spec --flat
# 抛出标准异常
@Get()
async findAll() {
throw new httpException('message', HttpStatus.FORBIDDEN)
}
# 创建异常过滤器
- 概述:内置的异常过滤器可以处理许多异常,但是可能需要对异常具有完全控制。例如:添加日志记录,或者不同异常返回不同JSON
- 需要实现抽象类
ExceptionFilter的catch()接口。 @Catch(HttpException)装饰器会将必要的元数据绑定到异常过滤器上,@Catch()可以接受单个参数,也可以是多个参数,可以同时为多种类型设置过滤器
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException
} from '@nestjs/common'
// T 表示异常的类型
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter<T> {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp() // 获取请求上下文
const response = ctx.getResponse()
const request = ctx.getRequest()
const status = exception.status()
response.status(status).json({
code: 500,
message: exception.message,
path: request.url
})
}
}
# 绑定异常过滤器
- 使用
UseFilters()装饰器。他可以也可以接受多个异常实例。也可以之间传递异常类。
import { UseFilters } from '@nestjs/common'
@Controller()
@UseFilters(HttpExceptionFilter)
export class TestController {
@Get('/test')
@UseFilters(new HttpExceptionFilter()) // 不推荐 尽量使用类来减少内存使用
say() {}
}
# 全局异常
// ...
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new HttpExceptionFilter())