0

Multer is a middleware package recommended by Express JS to upload files. Checking their error handling section they use this example:

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.
  })
})

And as you can see , that error handling example is executed within the regular code of the route. This is a problem for me because I need to handle those errors before executing two middleware functions that are like this

app.post('/profile', [middlewareFunctions.Authenticate,middlewareFunctions.getDataUploadedFile], function (req, res) {

})

So Basically my question is, Where can I use Multer's error handling section before my middleware gets executed?. Thank you

PS: Someone already posted this question on Stackoverflow but didn't specify correctly and with an example on how it was solved, and besides that the question was posted two years ago , so I don't think his answer is compatible with the current version of Multer.

1 Answers1

1

I've explored that "onError" function was removed long ago, and this will not work as well. So we need to use a manual and easy way for that.

I've some small snippet (simple server example) for handling multer errors. Just write the exact code-block after all app.use(...) middlewares like this:

const port = process.env.APP_PORT || 3001;
const http = require('http');
const express = require('express');
const app = express();

const multer = require('multer');

// Routes
// app.get('/', () => { ... });

// Handling errors for 404 not-founds
app.use((req, res) => {
    res.status(404).json({
        err_code: 404,
        err_message: "URL-endpoint not found!"
    });
});

// EXACT PART >>>
app.use((err, req, res, next) => {
    if (err instanceof multer.MulterError) { // Multer-specific errors
        return res.status(418).json({
            err_code: err.code,
            err_message: err.message,
        });
    } else { // Handling errors for any other cases from whole application
        return res.status(500).json({
            err_code: 409,
            err_message: "Something went wrong!"
        });
    }
});
// EXACT PART <<<

// Running the server
http.createServer(app);
app.listen(port, () => {
    console.log(`Server started on port ${port} !!!`);
});

In addition, you can use these multer standard messages for customization.

boolfalse
  • 1,892
  • 2
  • 13
  • 14
  • Thank you, the snippet helped me a lot. However, instead of using it exactly how you did it , I created a new middleware with your code and inserted in the middleware chain after the multer part to upload the file ``` app.post('/profile', [upload.single('file'),middlewareFunctions.handlingMulter,middlewareFunctions.Authenticate,middlewareFunctions.getDataUploadedFile], function (req, res) { }) ``` Where middlewareFunctions.handlingMulter is your snippet in another file – Esteban Delgado Sep 06 '21 at 12:19
  • it's good to refactoring your project files. I think [this](https://gist.github.com/lancejpollard/1398757) could be useful for you as well as me :) – boolfalse Sep 06 '21 at 12:35