You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义NestJS中FileInterceptor的异常返回信息?

自定义FileInterceptor异常返回格式的解决方案

在NestJS中,FileInterceptor依赖multer处理文件上传,超出限制时抛出的BadRequestException会被框架默认格式化。要改成你需要的格式,有两种常用方式:

方案一:全局异常过滤器(推荐,统一处理所有异常格式)

创建全局异常过滤器,拦截并重新格式化异常响应:

  1. 创建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,
    });
  }
}
  1. 在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();

方案二:局部异常过滤器(仅针对当前路由)

如果只需要修改单个路由的异常响应,可以直接在路由上使用局部过滤器:

  1. 复用上述的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 09:10:56