Home > Blockchain >  Express - Error Handling Doesn't Work with Async Function
Express - Error Handling Doesn't Work with Async Function

Time:01-19

So this is the POST request for /products, when a form is submitted, this function will be invoked. I use a try-catch to catch the error if the form is submitted wrongly.

This is my Schema.

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']
    }
});

The error is with the newProduct.save() line, so if I submit a form that goes against the Schema, like not having a name, I will get an error instead of getting redirected 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);
    }
});

This is my error handler.

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

CodePudding user response:

The save method is asynchronous and returns a promise. In your case, newProduct.save() returns a promise which is not being fulfilled and no error is actually thrown:

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

CodePudding user response:

The best solution would be validate req.body with a validator and save newProduct after it is validated. It'd be better to return the newProduct after it is saved rather than redirecting to certain endpoint.

If it is not validated you can throw your custom error.

I recommend using JOI which is very easy to use.

  • Related