主题
Exception Filter
Guard / Pipe / Service 抛出的异常,默认由 Nest 转成 JSON 错误响应。自定义 Filter 可统一错误格式。未知异常不应把堆栈、SQL、密钥等内部信息返回给客户端。
业务层用内置 HTTP 异常表达可预期错误:BadRequestException(400)、UnauthorizedException(401)、ForbiddenException(403)、NotFoundException(404)、ConflictException(409)。
ts
import { NotFoundException } from '@nestjs/common'
if (!note) {
throw new NotFoundException('Note not found')
}ts
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common'
import type { Response } from 'express'
@Catch()
export class HttpErrorFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse<Response>()
const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
const exceptionResponse = exception instanceof HttpException ? exception.getResponse() : null
const message =
typeof exceptionResponse === 'string'
? exceptionResponse
: typeof exceptionResponse === 'object' && exceptionResponse !== null && 'message' in exceptionResponse
? (exceptionResponse as { message: string | string[] }).message
: 'Internal server error'
response.status(status).json({
success: false,
statusCode: status,
message,
})
}
}@Catch() 不传参数时捕获全部异常;也可 @Catch(HttpException) 只处理指定类型。
注册
方法级 / Controller 级
ts
import { Controller, Get, UseFilters } from '@nestjs/common'
@Controller('notes')
export class NotesController {
@Get(':id')
@UseFilters(HttpErrorFilter)
findOne() {}
}ts
@UseFilters(HttpErrorFilter)
@Controller('notes')
export class NotesController {}全局
无依赖时:
ts
app.useGlobalFilters(new HttpErrorFilter())需注入日志等 Provider 时用 APP_FILTER,不要只用 new 丢进 useGlobalFilters:
ts
import { Module } from '@nestjs/common'
import { APP_FILTER } from '@nestjs/core'
import { HttpErrorFilter } from './http-error.filter'
@Module({
providers: [
{
provide: APP_FILTER,
useClass: HttpErrorFilter,
},
],
})
export class AppModule {}