【发布时间】:2021-12-19 05:25:13
【问题描述】:
我制作了一个控制器,控制器接收图像文件。但我想过滤图像扩展名(jpg/png/gif),然后我制作了一个图像过滤器函数,该函数可以正常工作,但是当函数抛出错误时。得到错误响应500 internal server error,但终端显示图像的实际错误Only image files are allowed!
我不能接受来自回调函数的错误来响应这个错误。 这里的任何回调解决方案都会返回错误
//this is Image Filter Function
export const imageFileFilter = (req, file, callback) => {
if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
return callback(new Error('Only image files are allowed!'), false);
}
callback(null, true);
};
控制器文件代码
@Post('/profile-image')
@UseInterceptors(FilesInterceptor('img', 1, { fileFilter: imageFileFilter }))
async profile(
@UploadedFile() file,
): Promise<string> {
return await this.prfile.upload(file);
}
【问题讨论】:
-
如果将
Error更改为BadRequestException会怎样?它仍然返回 500 还是现在是 400? -
@JayMcDoniel 感谢兄弟,我现在添加
BadRequestException它的工作
标签: node.js typescript express nestjs multer