oderfla
oderfla

Reputation: 1797

How to catch errors in multer

I have read documentation for multer. But the current set up I have in my code is different and this makes difficult for me to understand how to handle errors. It is important now because it happened (only once) that a file was not stored on the server but the code continued saving info in database as if the storing of the file had worked. But it probably did not.

const multer = require('multer');

var docPath = "path_to_disk_where_to_store_files";

var storage = multer.diskStorage({
    inMemory: true,
    destination: function (request, file, callback) {
        callback(null, docPath);
    },
    filename: function (request, file, callback) {
        //Just a function that creates an unique name with timestamp
        renamedFile = helpers.createUniqueName(file.originalname);
        callback(null, renamedFile);
    }
});

var fileFilter = function (req, file, cb) {
    var path = require('path');
    var ext = path.extname(file.originalname);
    if (file.mimetype !== 'application/pdf' || ext.toLowerCase() != '.pdf') {
        req.fileValidationError = 'goes wrong on the mimetype';
        return cb(null, false, new Error('goes wrong on the mimetype'));
    }
    cb(null, true);
};

const multerUploader = multer({storage: storage, fileFilter: fileFilter, limits: { fileSize: maxSize }});

router.post('/save_document',[multerUploader.single('file'),saveDocumentInDb]);

I dont really understand where the if-statement that will check if the upload got an error would fit.

Upvotes: 3

Views: 6844

Answers (1)

shubham
shubham

Reputation: 449

Please refer the following for error handling when using multer: https://github.com/expressjs/multer#error-handling

Your implementation will be something like this:

const multerUploader = multer({storage: storage, fileFilter: fileFilter, limits: { fileSize: maxSize }});
const upload = multerUploader.single('file');
router.post('/save_document', 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 and save document in DB here.
  })
})

Upvotes: 10

Related Questions