Solving the Issue of Error Handling Not Functioning Properly with Async Functions in Express

Here is the POST request for /products. When a form is submitted, this function will be triggered, utilizing try-catch to handle any errors that may occur if the form is submitted incorrectly.

This is the Schema being used:

const productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true,
        min: 0
    },
    category: {
        type: String,
        lowercase: true,
        enum: ['fruit', 'vegetable', 'dairy']
    }
});

If there is an issue with the newProduct.save() line, such as submitting a form that violates the Schema by not including a name, an error will be generated instead of redirecting to the page.

app.post('/products', (req, res, next) => {
    try {
        const newProduct = new Product(req.body);
        newProduct.save();
        res.redirect(`/products/${newProduct._id}`);
    }
    catch (e) {
        next(e);
    }
});

Below is my error handling middleware:

app.use((err, req, res, next) => {
    const { status = 500, message = 'Something went wrong!' } = err;
    res.status(status).send(message);
});

Answer №1

When utilizing the save method, it's important to note that it operates asynchronously and returns a promise. In this specific scenario, the call to newProduct.save() results in a promise that is not resolved and does not trigger any errors:

app.post('/products', async (req, res, next) => {
    try {
        const newProduct = new Product(req.body);
        await newProduct.save();
        res.redirect(`/products/${newProduct._id}`);
    }
    catch (e) {
        next(e);
    }
});

Answer №2

The ideal approach involves validating the req.body using a validator and saving newProduct only after successful validation. Rather than redirecting to a specified endpoint, it is advisable to return the saved newProduct.

If validation fails, you can throw a custom error.

I suggest utilizing JOI, which offers simplicity in its usage.

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

React Native - Implementing asynchronous array filtering using async/await

In my code, there is a filtering method implemented as follows: _filterItems(items) { return items.filter(async item => { let isTrue = await AsyncStorage.getItem('key'); return isTrue; }) } However, when calling the method this._ ...

The request for PUT, POST, and DELETE methods has been terminated

Issue Encountering the following problem: https://i.sstatic.net/aUF0m.png Scenario Pinning down the exact reason and providing detailed information is proving to be a challenge. In essence, the setup involves an Angular + Express.js application, MySQL f ...

Embedding an Iframe in Angular 2 directly from the database

Looking for assistance with iframes in Angular 2. Initially, embedding an iframe directly into a component's template functions correctly. <iframe src='http://plnkr.co/edit/zZ0BgJHvQl5CfrZZ5kzg?p=preview | safeUrl' allowtransp ...

"Leaflet automatically refreshes tile cache when zooming in or out

Currently, I'm facing an issue regarding the tile cache in leaflet. If I move from point A to point B, and examine the tiles in between, they are cached without any problems. However, if I go from A to B, zoom in and out, and then return to point A, ...

Utilize the "include" statement within the sequelize framework to

Essentially, I have a UserLadder model that contains a nested User model: try { const leaderboard = await UserLadder.findAll({ where: { weeklyLadderId: req.params.id, }, limit: req.params.playersNumber, attributes: [&a ...

Is there a foolproof method to confirm the validity of this string as JSON?

I am currently developing an application that requires a function to validate whether a given string parameter is valid JSON. The challenge lies in handling JSON data copied from Jira. For example, the JSON might appear as follows: "{ "query& ...

Challenges arise when trying to use multiple loops to add elements to an array

I am currently working with Angular/Typescript and utilizing the amcharts library version 4, specifically focusing on the multi line graph feature. When constructing the chart data, I have noticed that it only functions correctly with a single push to the ...

Adjust the hue of a single side of the cube with THREE.js

I'm currently delving into the world of OOP with Three.js, which is proving to be quite challenging. To start, I decided to create a box within the scene. Now, my next goal is to change the color of one face of that cube. var scene = new THREE.Scene( ...

Troubleshooting: Issues with Three.js Node TextureLoader

Currently, I am working on rendering objects server-side using node with three.js. I have successfully implemented the OBJLoader and MTLLoader, and I am utilizing MockBrowser to simulate the DOM. Strangely, when I take a screenshot of the model, I can se ...

Showing pictures from a JSON source

I am currently facing an issue while trying to display the cover art along with the search results. There seems to be a problem in the img src tag that is preventing the app from loading properly. Interestingly, when I direct the img to data.tracks[i].albu ...

How to handle errors with multer's ".fields" property

I'm having trouble figuring out how to handle errors with multer using the ".fields" property. The user needs to upload 4 photos, and I am using the .fields property to upload them to my MongoDB database. Here is the configuration file for multer cal ...

Simplify code by eliminating uuid references

Greetings! I am currently working with some code that is generated within a JSP tag and utilizes the jQuery data function to connect data with a div element. In order to link the jQuery script with the div on the webpage, I have employed a UUID. However, ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

The validation message from the requiredfieldvalidator is persisting even after filling the textbox with javascript

Is the textbox empty or not when using RequiredFieldValidator? When clicking the submit button, an error message appears but if the textbox is filled using javascript and then clicked elsewhere, the error message does not disappear. However, if something ...

Custom virtual properties can be set in Mongoose by utilizing the return value in a callback function

I've been searching all over for a solution to my issue, but I can't seem to find the right answer. I'm currently using MongooseJS as my ODM and I'm attempting to create virtual getters that can retrieve, process, and display informatio ...

Update the node server's URL address

After successfully deploying my first AngularJS application on Heroku using Node.js, I have encountered a small issue regarding the URL. Currently, the site is accessible at . But I would prefer it to be accessed at . How can I achieve this change? var ...

Trouble with incorporating numbers into Titanium

I have a query about adding a decimal number to a latitude value obtained using forwardGeocoder. Here's the code snippet I am referring to: Ti.Geolocation.forwardGeocoder(textField.value, function(e) { var a = e.latitude; var ...

Altering the appearance of the xy axis on a line chart in Chart.js version 4 by either removing it entirely or adjusting its color

I am facing an issue with my chart.js code where I am trying to remove both the axis lines from the graph but still display the grids (NOTE) ` const MAINCHARTCANVAS = document.querySelector(".main-chart") new Chart(MAINCHARTCANVAS, { type: 'line&apo ...

Setting a JavaScript variable to null

Using Jquery, I have a variable that is assigned a value on button click. After the code executes successfully, I need to reset the variable to null. $("#btnAdd").click(function () { var myDataVariable= {}; myDataVariable.dataOne="SomeDa ...

When sending an ajax request with HTML data as the payload

While working on an MVC program, I encountered an issue when trying to send data from a TextArea to the controller upon a button click. Everything worked fine until I had HTML-based data inside the TextArea. Here's a snippet of the HTML code: <te ...