如何创建一个自定义异常过滤器来处理业务逻辑异常(如 UserNotFoundException)?
解读
在国内一线/二线互联网公司的 NestJS 岗位面试中,这道题通常出现在「框架深度」环节,面试官想验证三件事:
- 你是否理解 NestJS 异常体系与 HTTP 异常之间的映射关系;
- 你是否能优雅地把「业务语义」翻译成「客户端友好」的响应格式;
- 你是否具备可扩展、可测试的工程化思维(日志、国际化、错误码、Sentry 上报等)。
只回答“继承 ExceptionFilter 实现 catch”只能拿到 60 分;把异常过滤器做成可配置、可复用、可插拔的模块,并给出单元测试写法,才能拿到 90+。
知识点
- ExceptionFilter 接口与 @Catch() 装饰器
- HttpException / RpcException / WSException 的继承链
- ArgumentsHost 与 host.switchToHttp() 的用法
- IoC 容器:让过滤器拿到 ConfigService、Logger、i18n Service
- 全局过滤器注册方式:main.ts useGlobalFilters vs AppModule providers
- 错误码规范:国内大厂普遍要求 { code, message, data, traceId, timestamp } 五段式
- 测试:@nestjs/testing 创建 Test Module,用 supertest 触发异常断言返回体
答案
- 定义业务异常基类(统一错误码规范)
// src/exceptions/business.exception.ts
export class BusinessException extends Error {
readonly code: string;
readonly status: number;
constructor(code: string, message: string, status = 400) {
super(message);
this.code = code;
this.status = status;
}
}
// 具体异常
export class UserNotFoundException extends BusinessException {
constructor(userId: string) {
super('USER_NOT_FOUND', `用户 ${userId} 不存在`, 404);
}
}
- 编写过滤器(支持日志、i18n、traceId)
// src/filters/business-exception.filter.ts
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { BusinessException } from '../exceptions/business.exception';
import { v4 as uuid } from 'uuid';
@Catch(BusinessException)
export class BusinessExceptionFilter implements ExceptionFilter {
private readonly logger = new Logger(BusinessExceptionFilter.name);
catch(exception: BusinessException, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const traceId = request.headers['x-trace-id'] || uuid();
const { code, message, status } = exception;
const body = {
code,
message,
data: null,
traceId,
timestamp: new Date().toISOString(),
path: request.url,
};
this.logger.error(
`[${traceId}] ${code}: ${message}`,
exception.stack,
BusinessExceptionFilter.name,
);
response.status(status).json(body);
}
}
- 注册为全局过滤器(推荐在 AppModule 层做,可注入依赖)
// src/app.module.ts
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { BusinessExceptionFilter } from './filters/business-exception.filter';
@Module({
providers: [
{
provide: APP_FILTER,
useClass: BusinessExceptionFilter,
},
],
})
export class AppModule {}
- 在 Service 中抛异常
throw new UserNotFoundException(id);
- 单元测试(Jest + supertest)
it('应返回 404 标准错误体', () => {
return request(app.getHttpServer())
.get('/users/999')
.expect(404)
.expect((res) => {
expect(res.body).toMatchObject({
code: 'USER_NOT_FOUND',
message: '用户 999 不存在',
data: null,
traceId: expect.any(String),
timestamp: expect.any(String),
path: '/users/999',
});
});
});
拓展思考
- 多协议统一:如果项目同时暴露 HTTP 与 gRPC,可把 BusinessException 映射到 RpcException,并在微服务端再写一个 RpcExceptionFilter,做到“一套业务异常,多端消费”。
- 国际化:把 message 字段抽离到 i18n 文件,过滤器里通过 request.headers['accept-language'] 动态取值,满足国内出海业务需求。
- 错误码治理:在 Monorepo 里建立 shared/constants/error-code.ts,用枚举集中管理,避免各业务线重复定义。
- 监控闭环:在过滤器里注入 SentryService,对 5xx 与核心 4xx 做自动上报;同时把 traceId 写入响应头,前端报错时回捞日志,实现“用户反馈—追踪—定位”闭环。
- 性能优化:对已知高频异常(如参数校验失败)做内存级缓存,减少重复 new Error 的开销;过滤器内部使用 fast-json-stringify 预编译返回模板,提升高并发场景序列化性能。