Search code examples
expressmiddlewaremulterexpress-router

Express router with middleware error handling


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?


Solution

  • 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()
        }
    }