如何修改NestJS中文件上传超限的Unexpected field错误提示?
NestJS 替换文件上传数量超限的错误提示
你遇到的"Unexpected field"错误是multer库抛出的,当上传文件数量超过FilesInterceptor设置的上限(这里是5个)时触发。要替换成自定义提示,可以通过以下两种方式实现:
方法一:自定义文件拦截器
继承FilesInterceptor并重写错误处理逻辑,在拦截器层面捕获超限错误并抛出自定义异常:
import { FilesInterceptor } from '@nestjs/platform-express'; import { BadRequestException } from '@nestjs/common'; import { MulterError } from 'multer'; export class CustomFilesInterceptor extends FilesInterceptor('files', 5) { async intercept(context, next) { try { return await super.intercept(context, next); } catch (error) { // 匹配multer的文件数量超限错误码 if (error instanceof MulterError && error.code === 'LIMIT_UNEXPECTED_FILE') { throw new BadRequestException('最多只能上传5个文件'); } // 其他错误原样抛出 throw error; } } }
然后在控制器中使用这个自定义拦截器替代原有的FilesInterceptor:
@Post('files') @UseInterceptors(CustomFilesInterceptor) async uploadFiles() { // 你的上传逻辑 }
方法二:使用异常过滤器
创建全局或控制器级别的异常过滤器,专门捕获multer抛出的错误并返回自定义响应:
import { ExceptionFilter, Catch, ArgumentsHost, BadRequestException } from '@nestjs/common'; import { MulterError } from 'multer'; @Catch(MulterError) export class MulterExceptionFilter implements ExceptionFilter { catch(exception: MulterError, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); if (exception.code === 'LIMIT_UNEXPECTED_FILE') { response.status(400).json({ statusCode: 400, message: '最多只能上传5个文件', error: 'Bad Request' }); } else { // 处理其他multer错误(比如文件大小超限等) response.status(400).json({ statusCode: 400, message: exception.message, error: 'Bad Request' }); } } }
注册过滤器
- 控制器级别:在目标接口上添加
@UseFilters装饰器
@Post('files') @UseInterceptors(FilesInterceptor("files", 5)) @UseFilters(MulterExceptionFilter) async uploadFiles () { // 你的上传逻辑 }
- 全局级别:在
main.ts中注册,对所有接口生效
async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalFilters(new MulterExceptionFilter()); await app.listen(3000); } bootstrap();
内容的提问来源于stack exchange,提问作者user22128783
相关产品推荐
相关产品推荐

