0

I have a question about error handling with middleware, specifically multer. I have this route:

router.post('/', saveFile, (req, res, next) => {
    //rest of code
    })

Then I have saveFile middleware:

const multer = require('multer')
const storage = multer.diskStorage({
    destination: (req, res, cb) => {
        cb(null, './uploads/')
    },
    filename: (req, res, cb) => {
        cb(null, new Date().getTime() + '.jpg')
    }
})

const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/jpeg') cb(null, true)

    cb(null, false)
}
const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 3 // up to 3 megabytes
    },
    fileFilter: fileFilter
})

const saveFile = upload.single('file')
module.exports.saveFile = saveAudio

The issue I have is that when I upload a file with a field name other than file, I get an error MulterError: Unexpected field. I want to catch this error somehow. But I don't even know where to do that. How do I do that?

irondsd
  • 1,140
  • 1
  • 17
  • 34
  • It seems that you are defining the expected name of the file field here: `upload.single('file')`? Just update the name 'file' to whatever you are expecting. – Adam Patterson Sep 25 '19 at 13:30
  • I know that. I don't have an error while using it normally. I want to catch an error in case there's one. – irondsd Sep 26 '19 at 09:10

1 Answers1

0

The answer was pretty simple, yet nobody answered.

in the app.js where express is setup, you can make a middleware for handling errors

app.use((error, req, res, next) => errorHandlers(error, req, res, next))

And put it at last.

and then ErrorHandlers.js:

module.exports = function(error, req, res, next) {
    if (error.name === 'MulterError') {
        // handle error here
    } else {
        next()
    }
}

irondsd
  • 1,140
  • 1
  • 17
  • 34