【问题标题】:how can I get handle errors from UseInterceptors Decorator如何从 UseInterceptors Decorator 获取处理错误
【发布时间】: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


【解决方案1】:

问题是 Nest 的默认 Exception Filter 将任何不是 HttpException 实例(来自 Nest 的错误类)的错误视为 Internal Server Error 并且只发回 500。为了解决这个问题,您可以使用HttpException 子类(如BadRequestException),或者您可以创建自己的异常过滤器来读取错误并发送适当的响应。这两种方法都很好,但HttpException 方法更直接

【讨论】:

    【解决方案2】:

    下班后添加BadRequestException时正确

    //this is Image Filter Function
     export const imageFileFilter = (req, file, callback) => {
     if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
       return callback(
       new BadRequestException('Only image files are allowed!'),
       false,
     );
     }
       callback(null, true);
     };
    

    【讨论】:

      猜你喜欢
      • 2011-06-01
      • 2012-02-11
      • 2018-10-24
      • 2019-07-23
      • 2018-08-13
      • 2020-09-15
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多