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.

Error handling not working

See original GitHub issue

Hello ! I want to be able to handle the limits and the fileFilter errors and I’m doing just as the doc says:

var upload = multer().single('avatar')

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err) {
      // An error occurred when uploading
      return
    }

    // Everything went fine
  })
})

My code looks like this

var upload = multer({ 
    dest: UPLOADS_DIR,
    limits: { fileSize: MAX_PIC_FILESIZE },
    fileFilter: ( req, file, cb ) => {
            cb( null, file.mimetype == 'image/jpeg' )
    },
});

// POST - uploading user profile picture
router.post( '/avatar', ( req, res ) => { 

    console.log( 'uploading' );
    upload.single( 'avatar', ( err ) => {

        if ( err )
        {
            console.log( err )
            return res.send({ error: 'file_too_large' })
        }

        console.log( 'uploaded file for', res.locals.userId, req.file.filename );

        var filename = res.locals.userId + '_' + App.getCurrentTimestamp() + '.jpg';
        fs.rename( req.file.path, UPLOADS_DIR + '/' + res.locals.userId, ( err ) => {

            if ( err )
            {
                console.log( err )
                return res.send({ error: 'file_too_large' })    
            }

            console.log( 'renamed file', UPLOADS_DIR + '/' + req.file.filename, filename )
            res.send({ url: PUBLIC_DIR + '/' + filename });

        });

    });

});

Bare in mind that it works perfectly if I remove the inner upload.single() and I add it as middleware:

router.post( '/avatar', upload.single('avatar'), ( req, res ) => { ... }

But then, the downside is I can’t get the error anymore. Any solution for this ? The uploading log gets triggered correctly, but it doesn’t fire the upload if not set as middleware.

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

21reactions
LinusUcommented, Aug 27, 2016

Sorry for not commenting on this earlier. The last example is really good, the reason the fileFilter thing isn’t showing up as an error is because it isn’t intended to. If you want to trigger an error, you can supply it to the callback, so something like this:

var multer = require('multer')({
  dest: App.uploadsDir,
  limits: { fileSize: App.maxMediaFileSize },
  fileFilter: (req, file, cb) => {
    if (file.mimetype !== 'image/jpeg') {
      return cb(new Error('Only jpeg images allowed'))
    }

    cb(null, true)
  }
})
var avatarUpload = multer.single('avatar')

router.post('/avatar', (req, res) => {
  avatarUpload(req, res, (err) => {
    if (err) return res.send({ error: 'invalid_file' })

    console.log('save the file', req.file)
  })
})

also, you shouldn’t call the avatarUpload twice! Either add it as a middleware or call it manually.

I hope this clears everything up, feel free to reopen if you have more problems 😃

1reaction
edicommented, Aug 25, 2016

Hi @wesbos I came up with the following code, which works just fine for me.

var multer  = multer({ 
             dest: App.uploadsDir, 
             limits: { fileSize: App.maxMediaFileSize }, 
             fileFilter: ( req, file, cb ) => { 
                      console.log( file.mimetype ); 
                      cb( null, file.mimetype == 'image/jpeg'  ) 
             }
        }),
    avatarUpload = multer.single('avatar');

router.post( '/avatar', avatarUpload, ( req, res ) => { 

    avatarUpload( req, res, ( err ) => {

        if ( err || !req.file )
             return res.send({ error: 'invalid_file' })

        console.log( 'save the file', req.file );

    });

});

Still, the err variable is empty when the fileFilter triggers ( at least it triggers ), so I’m checking if req,file is undefined in this case, which implies the file did not get through the filter, thus, returning an invalid_file error.

Hope it helps ( using node sharp to process the images ).

Read more comments on GitHub >

github_iconTop Results From Across the Web

Express 4 middleware error handler not being called
Not working on Firebase Functions... I created an app with all routes on that app and app.use(customErrorHandler) before exporting the app as a ......
Read more >
Fix your Express error handling now
There is a lot of ways to fix this issue. You can just put .catch after every handler. You can use Express 5,...
Read more >
Express error handling
Error Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler...
Read more >
A Guide to Error Handling in Express.js
Here's an outline of what we'll be covering so you can easily navigate or skip ahead in the guide: How does Error Handling...
Read more >
Custom error handler never called #2718 - expressjs/express
Hello, I am currently having trouble defining a simple custom error handler for some simple project. Here is my code: var express ...
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