question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

MulterError class doesn't allow custom messages.

See original GitHub issue

https://github.com/expressjs/multer/blob/a04f29376aba2ecf7062ff6a00749a4afb39db78/lib/multer-error.js#L16

I didn’t expect this behavior. I expected it to create a custom message that I provided. File type not supported! I am checking meme types using the filter. I thought I could use the MulterError class to nicely catch and organize its errors.

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:1
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

6reactions
JemiloIIcommented, Oct 15, 2018

So in the multer config

We can do this:

const upload = Multer({
    dest: '...'
    limits: { ... }.
    fileFilter(req, file, callback) { ... }
})

For limits, any limits check that fails will throw a multer error. For fileFilter, inorder for it to fail, we either add an error to the callback function or return false. I see false good for multiple files uploads that we do not want to stop all the uploads. So where does this error end up going when using express? Well to the last middleware express designates for error handling.

app.use((error, req, res, next)) {
    // error will not be a Multer error.
    if (error instanceof MulterError) {
        res.status(400).send({error: 'File not supported!'});
    } else {
        res.sendStatus(500);
    }
});

When we try and use the Multer error handler, it doesn’t use the provided error because

this.message = errorMessages[code]

I handle my server errors in this fashion and for my own custom errors I create, I would add a status property and other properties so that i can do something like this:

if (error instanceof MyError) {
    res.status(error.status).send({error: error.message, file: error.originalname});
}
0reactions
halaincommented, Apr 30, 2020

@anuraghazra solution work form mi,

#ImageFilter function

const imageFilter = (req: Request , file: Express.Multer.File, cb: Function) => {
    if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
         cb( new multer.MulterError("LIMIT_UNEXPECTED_FILE") , false);
    }else {
        cb(null, true);
    } 
}

#Express handlerError

server.app.use((err:Error, req: Request, res: Response, next: NextFunction) => {
    console.error(err.stack);
   
    //Catch multer error
    if (err instanceof multer.MulterError) {
        let message: string = '';
        if (err.code === 'LIMIT_FILE_SIZE'){ message='Archivo excede el tamaño permitido' };
        if (err.code === 'LIMIT_FILE_COUNT'){ message='No debe exceder el numero máximo de archivos' };
        if (err.code === 'LIMIT_UNEXPECTED_FILE'){ message='Tipo de archivo no permitido' };
        return res.status(400).json({
            ok: false,
            message: message.length ? message : err.message
        })
    }
        
    res.status(500).send('Server error!');
});

Sorry for my english

Read more comments on GitHub >

github_iconTop Results From Across the Web

Error handling when uploading file using multer with expressjs
You can use onFileUploadComplete to log a message when the upload is done, and compare that to when your route handler is called....
Read more >
Fix "Unexpected field" Error From Multer - Maxim Orlov
Learn how to decypher & fix this cryptic error message from multer, and finally implement working file uploads in Node.js.
Read more >
Multer: Easily upload files with Node.js and Express
In this article, we'll learn the purpose of Multer in handling files in submitted forms. We'll also explore Multer by building a mini...
Read more >
Handling File Uploads in Node.js with Express and Multer
Project Setup. Since we won't be storing our images in a database, but rather a simple folder for brevity and simplicity, let's make...
Read more >
Using Multer for File Uploads in Node.js | by Uriel Rodriguez
The first thing to note is the imports that allow separating the User routes into its ... return cb(new Error('some custom error message');...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found