Home > OS >  I don't know how to handle errors in Multer with Express
I don't know how to handle errors in Multer with Express

Time:02-18

I am using Multer to upload a maximum of 3 images to the server and it works fine, but when I upload more than 3 images, Multer tells me the error but it is not manageable to show the user.

I'm working on the route that calls the controller but in the Multer documentation it only shows how to handle errors with the route along with the controller actions.

Route:

router.post('/', upload.array('pictures', 3), 
    newProduct
);

Documentation code for handling Multer errors:

const multer = require('multer')
const upload = multer().single('avatar')

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }

    // Everything went fine.
  })
})

Error response shown by Multer:

error

In this case how could I do the same documentation but separately to handle Multer errors?

Thank you.

CodePudding user response:

Here multer gives you a middleware to handle the incoming multipart/form-data

const multer = require('multer')
const upload = multer().single('avatar')

You can fix your problem by creating a middleware wrapper to the middleware given by the multer package.

const multer = require('multer');

const uploadMiddleware = (req,res,next)=>{
  
  const upload = multer().array('pictures', 3);

  // Here call the upload middleware of multer
  upload(req, res, function (err) {
     if (err instanceof multer.MulterError) {
       // A Multer error occurred when uploading.
       const err = new Error('Multer error');
       next(err)
       } else if (err) {
       // An unknown error occurred when uploading.
       const err = new Error('Server Error')
       next(err)
     }

    // Everything went fine.
    next()
  })

}

Here with next() you can handle the multer related error your way

And on your routes you can simply use it like this

router.post('/', uploadMiddleware, 
  newProduct
);
  • Related