I want to make a filter for uploaded files using multer package, and my validation works.
But I want when user send wrong files, I return statusCode and message together.
NOTE: I can send message or send statusCode but I want send both.
here is my code
import { v4 as uuidv4 } from "uuid"
import multer from "multer";
const AVAILABLE_IMAGE_FORMATS = ["image/jpg", "image/jpeg", "image/png", "image/gif"]
const __dir_images__ = `${__dirname__}/../uploads/images`
class HandledRespError {
constructor(statusCode = 500, message = Messages.failed) {
return {
statusCode: statusCode,
message: message
}
}
}
const multerStorageFileName = function(req, file, cb) {
const uniqueName = uuidv4() "--" file.originalname
return cb(null, uniqueName)
}
const imageStorage = multer.diskStorage({
destination: __dir_images__,
filename: multerStorageFileName
});
const imageFileFilter = function(req, file, cb) {
if ( ! AVAILABLE_IMAGE_FORMATS.includes(file.mimetype) ) return cb(new HandledRespError(406), false) // I think my problem is here
cb(null, true)
}
export const imageUpload = multer({storage: imageStorage, fileFilter: imageFileFilter})
if I use return cb( "my message", false)
or return cb( new Error("my message"), false)
it will return my message with statusCode 500.
if I send return cb({statusCode:406, message: "my message"}, false)
or return cb({status:406, message: "my message"}, false)
, it will return statusCode 406 and message will be [object object]
how can I handle both statusCode and message together?
CodePudding user response:
Set the statusCode
property on the error object rather than passing it as a parameter:
var err = new Error("error 406");
err.statusCode = 406;
return cb(err);