Reputation: 99
I am throwing an error from multer-gridfs-storage , but not sure about handling it in a better way .
My Code :-
const storage = new gridfsStorage({
url : 'mongodb://localhost:27017/uploadeditems' ,
options : { useNewUrlParser : true , useUnifiedTopology : true } ,
file : (req , file) => {
if(file.mimetype === 'image/jpeg') {
return {
filename : file.originalname,
bucketName : 'Images' ,
metadata : {
ownername : "Anshu Anand"
}
}
}
else if(file.mimetype === 'application/pdf') {
return {
filename : file.originalname ,
bucketName : 'projectPDFs'
}
}
else {
throw new Error("File type is different")
}
}
})
upload = multer({
storage ,
})
My api to handle it :-
app.post('/upload' , upload.single('project') , async (req, res) => {
console.log(req.file)
res.render('upload' , {
msg : "File has been uploaded successfully"
})
} ,
(err , req , res , next ) => {
console.log(err)
return res.send(err) //gives just this :- storageError : []
)
console.log(err) output :-
Error: File type is different
at GridFSStorage.file [as _file] (F:\Node Projects\upload-download\index.js:41:19)
at GridFSStorage._generate (F:\Node Projects\upload-download\node_modules\multer-gridfs-storage\lib\gridfs.js:472:18)
at GridFSStorage.fromStream (F:\Node Projects\upload-download\node_modules\multer-gridfs-storage\lib\gridfs.js:368:35)
at GridFSStorage.fromFile (F:\Node Projects\upload-download\node_modules\multer-gridfs-storage\lib\gridfs.js:353:15)
at GridFSStorage._handleFile (F:\Node Projects\upload-download\node_modules\multer-gridfs-storage\lib\gridfs.js:314:9)
at F:\Node Projects\upload-download\node_modules\multer\lib\make-middleware.js:144:17
at allowAll (F:\Node Projects\upload-download\node_modules\multer\index.js:8:3)
at wrappedFileFilter (F:\Node Projects\upload-download\node_modules\multer\index.js:44:7)
at Busboy.<anonymous> (F:\Node Projects\upload-download\node_modules\multer\lib\make-middleware.js:114:7)
at Busboy.emit (node:events:376:20)
at Busboy.emit (F:\Node Projects\upload-download\node_modules\busboy\lib\main.js:38:33)
at PartStream.<anonymous> (F:\Node Projects\upload-download\node_modules\busboy\lib\types\multipart.js:213:13)
at PartStream.emit (node:events:376:20)
at HeaderParser.<anonymous> (F:\Node Projects\upload-download\node_modules\dicer\lib\Dicer.js:51:16)
at HeaderParser.emit (node:events:376:20)
at HeaderParser._finish (F:\Node Projects\upload-download\node_modules\dicer\lib\HeaderParser.js:68:8) {
storageErrors: []
}
So how do I handle it in a better way and send my exact error which is being thrown in storage config ?
Thanks in advance for any help .
Upvotes: 3
Views: 651
Reputation: 99
I found out how to get that exact message . You can get it on message property of err .
console.log(err.message) //=>File type is different
Upvotes: 0