NestJS中@UseFilters绑定RpcExceptionFilter不生效问题排查
问题根因
- 核心问题1:Controller 层手动捕获异常后未向外抛出
你在testException方法里用try/catch包裹了RPC调用逻辑,catch分支仅打印了日志,既没有返回自定义响应,也没有将捕获的异常重新抛出。异常被手动吞掉后,不会进入后续的RpcExceptionFilter处理流程,自然不会触发过滤逻辑。 - 问题2:异常过滤器实现不符合NestJS规范
HTTP层的异常过滤器catch方法要求接收两个参数,第二个参数是ArgumentsHost实例,用于获取当前请求上下文。你当前的实现仅传了第一个异常参数,会导致过滤器无法被NestJS正确识别执行。 - 问题3:返回字段拼写错误,和预期不符
你过滤器里返回的状态码字段拼写为staus(缺了字母t),同时响应的错误信息字段是error,和你预期的message字段不一致,哪怕过滤器生效也拿不到预期格式。
修复步骤
- 调整
testException方法,要么移除手动try/catch,要么在catch分支重新抛出异常:
@Get('test-exception') @HttpCode(HttpStatus.OK) @UseFilters(RpcExceptionFilter) async testException() { // 直接返回调用结果,异常会自动抛给过滤器处理 return await lastValueFrom(this.testRMQ.send('test', {})); } // 若需要保留日志打印,也可以这么写 async testException() { try { return await lastValueFrom(this.testRMQ.send('test', {})); } catch (error) { console.log(error); throw error; // 手动抛出异常让过滤器处理 } }
- 修正
RpcExceptionFilter的实现,补全参数和返回字段:
import { Catch, ExceptionFilter, ArgumentsHost } from "@nestjs/common"; import { RpcException } from "@nestjs/microservices"; import { Response } from 'express'; @Catch(RpcException) export class RpcExceptionFilter implements ExceptionFilter { catch(exception: RpcException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse<Response>(); // 也可以直接返回对象,Nest会自动序列化,这里用Response对象更灵活可控 return response.status(500).json({ status: 500, message: 'RpcFilterError' }); } }
修改完成后即可得到预期的响应结果。
内容的提问来源于stack exchange,提问作者utf_8
相关产品推荐
相关产品推荐

