Search code examples
node.jsexpresserror-handlingmulter

Unable to handle Multer using express error handler


I have tried to handle error in the following way but it is not working . What's wrong with it ?

const storage = new gridfsStorage({
    url : 'mongodb://localhost:27017/uploadeditems' ,
    file : (req , file) => {
        if(file.mimetype === 'image/jpeg') {
            return {
                filename : file.originalname,
                bucketName : 'Images'
            }
        }
        else if(file.mimetype === 'application/pdf') {
            return {
                filename : file.originalname , 
                bucketName : 'projectPDFs'
            }
        }

        else {
            return null
        }
    }
})


upload = multer({storage })


app.get('/' , (req , res) => {
    res.render('upload')
})

app.post('/upload' , upload.single('pproject')  , async (req, res) => {

    res.render('upload' , {
            msg : "File has been uploaded successfully"
        })
} ,

(err , req , res) => {
  res.json({
    msg : "Some error occured"})
)

I am assuming if some error occurs , upload.single() will call next(err) , which will be caught by the last error handler .


Solution

  • When multer calls next(err) in your circumstance, it does NOT continue on to the next middleware on your request handler. Instead, it goes to the error handler installed on Express at the top level as in:

    app.use(function (err, req, res, next) {
      console.error(err.stack)
      res.status(500).send('Something broke!')
    });
    

    See express doc on this here.

    If you don't have an express error handler installed, then it goes to the default express error handler.

    If you want to handle the error locally within this request handler, then you use the calling convention as shown in your previous question where you call upload(req, res, function(err) { ...}) manually and pass it your own next() handler so you can detect and intercept locally any errors in your own next callback function.