在抛出自定义异常时,如何确保前端能接收到结构化的错误响应(如 { code: 'USER_NOT_FOUND', message: '...' })?
解读
面试官想确认三件事:
- 你是否知道 NestJS 默认异常过滤器只认 HttpException,其他异常会被转成大而空的 500。
- 你是否能把“业务语义”与“HTTP 状态码”解耦,让前端拿到统一、可枚举、可国际化的错误码。
- 你是否能在微服务、GraphQL、WebSocket 等多场景下复用同一套异常体系,而不是在 controller 里手写 try-catch 拼响应。
国内项目普遍要求“错误码规范”落地到监控告警、多端翻译、用户提示,因此这道题是“高阶必问”。
知识点
- HttpException 与 BusinessException 的继承关系
- ExceptionFilter 接口、@Catch() 装饰器、ArgumentsHost
- 全局过滤器 APP_FILTER 与作用域(全局、模块、控制器、方法)
- BaseException 基类设计:code、message、data、traceId、i18nKey
- 内容协商:JSON vs GraphQL vs RPC 响应格式差异
- 日志链路:接入 SLS/ELK,把 code 作为索引字段
- Swagger 文档自动生成:@ApiResponse({ schema: { $ref: '#/components/schemas/ErrorBody' } })
- 国际化:I18nService 在过滤器里动态替换 message
- 统一返回包装:@UseInterceptors(ClassSerializerInterceptor) 与自定义拦截器冲突解决
答案
- 定义业务基类
export class BizException extends HttpException {
readonly code: string;
readonly data?: unknown;
constructor(code: string, message: string, status = HttpStatus.BAD_REQUEST, data?: unknown) {
super({ code, message, data, timestamp: new Date().toISOString() }, status);
this.code = code;
this.data = data;
}
}
- 创建全局过滤器(支持 GraphQL 与 REST 双协议)
@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
constructor(private readonly i18n: I18nService, private readonly logger: MyLogger) {}
catch(exception: unknown, host: ArgumentsHost): void {
const ctx = host.getType() === 'graphql' ? GqlArgumentsHost.create(host) : host;
const response = ctx.getResponse();
const request = ctx.getRequest();
const traceId = request.headers['x-trace-id'] ?? uuid();
let body: any;
let status: number;
if (exception instanceof BizException) {
status = exception.getStatus();
const msg = this.i18n.t(`error.${exception.code}`, { lang: request.headers['accept-language'] });
body = { code: exception.code, message: msg, data: exception.data, traceId };
} else if (exception instanceof HttpException) {
status = exception.getStatus();
body = { code: 'HTTP_ERROR', message: exception.message, traceId };
} else {
status = HttpStatus.INTERNAL_SERVER_ERROR;
body = { code: 'INTERNAL_ERROR', message: '服务器走神了', traceId };
this.logger.error(exception, request.url, traceId);
}
if (host.getType() === 'graphql') {
throw new ApolloError(body.message, body.code, body);
} else {
response.status(status).json(body);
}
}
}
- 在 AppModule 注册为全局
{
provide: APP_FILTER,
useClass: GlobalExceptionFilter,
}
- 使用方式
throw new BizException('USER_NOT_FOUND', '用户不存在', HttpStatus.NOT_FOUND);
前端收到的 JSON 一定是:
{
"code": "USER_NOT_FOUND",
"message": "用户不存在",
"data": null,
"traceId": "c0f8e9..."
}
拓展思考
-
如何防止“敏感信息”泄露到 body?
在过滤器里判断process.env.NODE_ENV === 'production',当 code 为 INTERNAL_ERROR 时,把 message 替换成固定文案,并把真实堆栈只打到日志。 -
微服务场景下,RPC 异常如何透传 code?
自定义RpcException子类,在MicroserviceExceptionFilter里把 code 塞进rpcException.getError(),消费端通过firstValueFrom捕获后可直接拿到同一套错误码。 -
错误码如何与权限系统联动?
把 code 设计为“三段式”:模块_场景_子码,如AUTH_LOGIN_USER_DISABLED,在网关层做码表映射,直接返回 403,减少后端重复判断。 -
前端 TypeScript 如何做到“错误码智能提示”?
在 monorepo 里共享@org/error-code包,通过as const导出码表,前端catch后可用switch (err.code)收窄类型,实现编译期检查。