如何自定义NestJS中FileInterceptor的异常返回信息?
自定义FileInterceptor异常返回格式的解决方案
在NestJS中,FileInterceptor依赖multer处理文件上传,超出限制时抛出的BadRequestException会被框架默认格式化。要改成你需要的格式,有两种常用方式:
方案一:全局异常过滤器(推荐,统一处理所有异常格式)
创建全局异常过滤器,拦截并重新格式化异常响应:
- 创建
http-exception.filter.ts文件:
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'; import { Response } from 'express'; @Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse<Response>(); const status = exception.getStatus(); const exceptionResponse = exception.getResponse(); // 处理multer的"Too many files"等特定错误,同时兼容其他HttpException let message = typeof exceptionResponse === 'string' ? exceptionResponse : (exceptionResponse as { message: string }).message; response.status(status).json({ code: status, message: message, }); } }
- 在
main.ts中注册全局过滤器:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { HttpExceptionFilter } from './http-exception.filter'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalFilters(new HttpExceptionFilter()); await app.listen(3000); } bootstrap();
方案二:局部异常过滤器(仅针对当前路由)
如果只需要修改单个路由的异常响应,可以直接在路由上使用局部过滤器:
- 复用上述的
HttpExceptionFilter,然后在目标路由上添加@UseFilters(HttpExceptionFilter):
import { HttpExceptionFilter } from './http-exception.filter'; @Post('single') @UseInterceptors( FileInterceptor('file', { limits: { files: 1 }}), ) @UseFilters(HttpExceptionFilter) // 添加这一行 async uploadFile(@UploadedFile() file, @GetUser('id') userId: number, @Body() dto) { this.logger.log('Upload file'); file.createdBy = userId; file.oldFileName = dto.oldFileName; return this.client.send('upload_file', file); }
说明
两种方案都会将你提到的超出文件数量限制的异常,格式化为:
{ "code": 400, "message": "Too many files" }
全局方案适合项目统一异常响应格式,局部方案适合特定路由的个性化处理。
内容的提问来源于stack exchange,提问作者Nguyen Phong
相关产品推荐
相关产品推荐

