Home > Enterprise >  how can I get handle errors from UseInterceptors Decorator
how can I get handle errors from UseInterceptors Decorator

Time:11-07

I make a controller that controller receives image files. but I want to filter image extension (jpg/png/gif) then I make an image filter function that function works correctly but when the function throw error. Getting error response 500 internal server error but terminal shows the actual error of the image Only image files are allowed!

I can't accept the error from the callback function to return response this error. any solution here to callback returns the error

//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);
}

CodePudding user response:

when add BadRequestException after work correclty

//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);
 };

CodePudding user response:

The issue is that Nest's default Exception Filter treats any error that is not an instance of HttpException (an error class from Nest) as an Internal Server Error and just sends back a 500. To combat this, you can either use an HttpException subclass (like BadRequestException) or you can create your own exception filter that will read the error and send the appropriate response. Both approaches are fine, but the HttpException approach is more straightforward

  • Related