Search code examples
node.jspromisesequelize.jstry-catch

Sequelize- Try block won't catch on model.create() error


I want to be able to reroute the website user if an error occurs in adding something to the database (a server-side validation error, like a string containing a non alphanumeric symbol or something). Currently the try-catch block doesn't catch anything even when the model.create() fails. How can I rewrite this to make it get out of the try-block and reroute back to '/' if an invalid entry is attempted? Here's what I have (btw, Request and Ride1 are the model names):

/* POST request */
router.post('/', function(req, res, next){

  /*a bunch of variable initializations to get form data*/

  try{
    Request.create({
      serial_num: serial_num,
      meter_reading: meter_reading,
      request_type: request_type
    })
      .catch(err => {
        throw err 
      })

    Ride1.create({
       serial_num: serial_num,
       meter_reading: meter_reading,
       request_type: request_type
     })
       .catch(err => {
         throw err 
       })

    res.redirect('/thankYou')
  }
  catch (e){
    console.log(e);
    res.redirect('/');
  }
});

The .catch(err =>...) stuff doesn't seem to do anything and was just a feeble attempt at getting this to work. I think I could do it if I didn't need to Any advice is much appreciated.


Solution

  • Use async/await and the express-async-wrap package:

    const wrap = require('express-async-wrap')
    ...
    router.post('/', wrap(async function(req, res, next){
     try{
        await Request.create({
          serial_num: serial_num,
          meter_reading: meter_reading,
          request_type: request_type
        })
    
        await Ride1.create({
           serial_num: serial_num,
           meter_reading: meter_reading,
           request_type: request_type
         })
    
        res.redirect('/thankYou')
      }
      catch (e){
        console.log(e);
        res.redirect('/');
      }
    }
    ));