如何从 UseInterceptors Decorator 获取处理错误
how can I get handle errors from UseInterceptors Decorator
我做了一个控制器,控制器接收图像文件。但我想过滤图像扩展名 (jpg/png/gif) 然后我制作了一个图像过滤器功能,该功能正常工作但当函数抛出错误时。收到错误响应 500 internal server error
但终端显示图像的实际错误 Only image files are allowed!
我无法接受来自回调函数的错误以 return 响应此错误。
此处回调 return 错误
的任何解决方案
//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);
};
Controller file code
@Post('/profile-image')
@UseInterceptors(FilesInterceptor('img', 1, { fileFilter: imageFileFilter }))
async profile(
@UploadedFile() file,
): Promise<string> {
return await this.prfile.upload(file);
}
添加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);
};
问题是 Nest 的默认 Exception Filter 将任何不是 HttpException
实例的错误(来自 Nest 的错误 class)视为 Internal Server Error
并且只是发送回 500。为了解决这个问题,您可以使用 HttpException
subclass(如 BadRequestException
)或者您可以创建自己的异常过滤器来读取错误并发送适当的回复。两种方法都很好,但 HttpException
方法更直接
我做了一个控制器,控制器接收图像文件。但我想过滤图像扩展名 (jpg/png/gif) 然后我制作了一个图像过滤器功能,该功能正常工作但当函数抛出错误时。收到错误响应 500 internal server error
但终端显示图像的实际错误 Only image files are allowed!
我无法接受来自回调函数的错误以 return 响应此错误。 此处回调 return 错误
的任何解决方案//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);
};
Controller file code
@Post('/profile-image')
@UseInterceptors(FilesInterceptor('img', 1, { fileFilter: imageFileFilter }))
async profile(
@UploadedFile() file,
): Promise<string> {
return await this.prfile.upload(file);
}
添加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);
};
问题是 Nest 的默认 Exception Filter 将任何不是 HttpException
实例的错误(来自 Nest 的错误 class)视为 Internal Server Error
并且只是发送回 500。为了解决这个问题,您可以使用 HttpException
subclass(如 BadRequestException
)或者您可以创建自己的异常过滤器来读取错误并发送适当的回复。两种方法都很好,但 HttpException
方法更直接