What is the best way to send an error back to ExpressJS from middleware?

Utilizing [Multer][1] as middleware for handling multipart form data, I am taking advantage of the configuration options it provides through diskStorage. This feature allows for error checking and control over file uploads within Multer.

The structure of my Express route is as follows:

expressRouter.post(['/create'],
    MulterUpload.single("FileToUpload"), // If an error occurs here, Express will return it to the user
    async function(req, res) {
      // Process form text fields in req.body here
});

MulterUpload.single() directs the file input field named "FileToUpload" for processing:

const MulterUpload = multer({
    storage: MulterStorage
)}

const MulterStorage = multer.diskStorage({
    destination: async function (req, file, cb) {
        try {
            if ("postID" in req.body && req.body.postID != null && req.body.postID.toString().length) {

                const Result = await api.verifyPost(req.body.postID)
                if (Result[0].postverified == false) {
                    const Err = new Error("That is not your post!");
                    Err.code = "ILLEGAL_OPERATION";
                    Err.status = 403;
                    throw(Err); // Unauthorized upload attempt
                } else {
                    cb(null, '/tmp/my-uploads') // Allowed upload
                }
            }
        } catch (err) {
            // How can I send this error back to Express for returning it to the user? The error remains unresolved due to the use of async/await.
        }
    }
    ,
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
})

I'm faced with the challenge of figuring out how to relay the error from MulterStorage back to Express, which would then present it to the browser/user as an error message. [1]: https://www.npmjs.com/package/multer

Answer №1

If you encounter an error, make sure to pass an Error object as the first argument in your completion callback function. Instead of

cb(null, someResult)

you should do:

cb(new Error("I encountered a disk error"));

By doing this, if multer is set up as plain middleware, it will automatically trigger next(err) and Express will handle the error using the generic error handler.

For more information and examples, check out these references:

https://www.npmjs.com/package/multer#error-handling

https://github.com/expressjs/multer/issues/336#issuecomment-242906859

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unable to access context property in null object (useContext)

When trying to incorporate {searchWord} from useContext into a function alongside an API call using getServerSideProps(), I encountered several errors. The latest one being: Cannot read properties of null (reading 'useContext'). I suspect there ...

MongoDB Atlas Via Compass could not be loaded on Ubuntu due to an error

After recently downloading MongoDB Compass on Ubuntu, I decided to use the connection string from MongoDB Atlas to connect using MongoDB Compass. Upon opening MongoDB Compass, it automatically detected the connection string that I accepted. I then entered ...

Is there a way to make the sidepanel appear and be edited with just one click on a Chrome extension, instead of the current two-click requirement?

Currently, I am in the process of developing a Chrome dictionary game extension. In the initial phase of the project, the user should have the ability to right-click on a word, triggering the display of a side panel containing definitions sourced from a lo ...

What is the best way to remove text from a box when a user clicks on it?

After successfully placing G in the selected box upon clicking it, I now want to work on removing it when clicked again. I'm encountering an issue with my current code - can anyone help me identify what's wrong and suggest a solution? Below is ...

Incorporate Stripe Elements into your Nuxt Js application

I recently managed to integrate Stripe into my React + Spring Boot application by following the guidelines provided in this documentation: https://stripe.com/docs/stripe-js/react. I used it in my React class component. Now, I am transitioning to Nuxt from ...

Discovering the worth of objects in a MongoDB array - a guide

I need assistance to access the value of a nested object within an array. I have the _id of the parent object and the _id of the child object in the array, but I am struggling to get the value of "solvedOn" in order to toggle a checkbox behavior. Here is ...

Using angularjs to recycle templates and connect them to various attributes in the identical scope

How can I efficiently reuse an express included template multiple times while selectively binding it to different properties of the scope? Here is an example of what I am trying to achieve: <div ng-show="isCoApplicant" bind-to="applicant in data.coAppl ...

Using JavaScript to load content with AJAX on skip links

Is there a way to prevent the error "loadWithAjax is not defined" from occurring while using the script below? addEventListener('click', function (ev) { if (ev.target.classList.contains('bpb')) { ev.preventDefault(); ...

How can we achieve the same functionality as React Native's { flex: 1 } in React JS?

I've been diving into React Native development, and now I'm exploring React.js for web applications. However, I'm facing a challenge in creating a simple View that takes up the entire screen to begin experimenting with different components. ...

What is the method for eliminating quotes from a URL?

Changing the URL: history.replaceState('data to be passed', 'Title of the page', '<?php echo getAddress(); ?>/?usp-custom-14="'+urldates+'"&usp-custom-8="'+title+'"'); After making changes, it s ...

Creating custom modals for individual elements using PHP

Currently, I am working on a project that involves allowing users to select an item from a list retrieved from a MySQL database. The goal is to have buttons generated based on the selected item, shown below: https://i.sstatic.net/Oi5CG.png Here is a trim ...

Code snippet for a click event in JavaScript or jQuery

I initially wrote the code in JavaScript, but if someone has a better solution in jQuery, I'm open to it. Here's the scenario: I have multiple questions with corresponding answers. I want to be able to click on a question and have its answer dis ...

Utilizing the Aladin Lite application within a React application, despite not being specifically designed for React

I am interested in incorporating the Aladin Lite app into my React application. Typically, embedding the app in a div is straightforward when developing a website without React: <!-- include Aladin Lite CSS file in the head section of your page --> ...

Header-driven redirection

I am using node js and express js. My goal is to ensure that if app.get does not have a token parameter, then an html file with js will be uploaded to pass the token. If the token is passed, then another html file should be displayed. However, I am unsure ...

Heroku Foreman unexpectedly stops while using Express.js bodyParser() function

After running foreman start, the following message is displayed: > foreman start 20:38:55 web.1 | started with pid 3896 20:38:55 web.1 | Development 20:38:56 web.1 | connect.multipart() will be removed in connect 3.0 20:38:56 web.1 | exited with co ...

Getting the value of a CSS variable under <script> in Vue.js

I am working on implementing a Doughnut chart using chartJs in my application. However, I want to set the color of the chart within the <script> tag and retrieve the color from theme/variables.css. In the current code snippet below, there is a hardc ...

Issue with Sequelize failing to update a row within a database table

This is my first experience using sequelize. Within my database, I have a table named feed containing columns such as ID, caption, and url. In my controller, there is a straightforward function aimed at updating a row within this table: router.patch(' ...

Organizing outcomes from a for each function into an array using javascript

I have a form with multiple values of the same name, and I need to arrange this data in an array before sending it via AJAX. However, when I try to do this using the .push function, I encounter an error that says "Uncaught TypeError: dArray.push is not a f ...

A solution for accessing computed properties within a v-for loop

Currently, I am facing a challenge with the code provided below. It seems that computed properties do not support parameters. Do you happen to have any suggestions on how to overcome this issue? I am considering using watchers on functions but I am also ...

`Why isn't Angular updating when watching window.pageYOffset?`

Within my controller, I have the following code: $scope.woffset = window.pageYOffset; $scope.$watch("woffset", function (newValue, oldValue) { console.log("hello"); console.log(window.pageYOffset); }, true); }); My expectation is to receive co ...