Sequelize- ลองบล็อกจะไม่ตรวจจับข้อผิดพลาด model.create()

ฉันต้องการให้เปลี่ยนเส้นทางผู้ใช้เว็บไซต์ได้หากมีข้อผิดพลาดเกิดขึ้นในการเพิ่มบางสิ่งลงในฐานข้อมูล (ข้อผิดพลาดในการตรวจสอบฝั่งเซิร์ฟเวอร์ เช่น สตริงที่มีสัญลักษณ์ที่ไม่ใช่ตัวอักษรและตัวเลขหรือบางอย่าง) ขณะนี้บล็อก try-catch ไม่สามารถตรวจจับสิ่งใดได้แม้ว่า model.create() จะล้มเหลวก็ตาม ฉันจะเขียนสิ่งนี้ใหม่เพื่อให้ออกจาก try-block และเปลี่ยนเส้นทางกลับไปที่ '/' ได้อย่างไรหากพยายามป้อนข้อมูลที่ไม่ถูกต้อง นี่คือสิ่งที่ฉันมี (btw, Request และ Ride1 เป็นชื่อรุ่น):

/* 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('/');
  }
});

ดูเหมือนว่าสิ่งต่าง ๆ .catch(err =>...) จะไม่ทำอะไรเลยและเป็นเพียงความพยายามเล็กน้อยในการทำให้สิ่งนี้ใช้งานได้ ฉันคิดว่าฉันทำได้ถ้าฉันไม่ต้องการคำแนะนำใด ๆ ที่ชื่นชมมาก


person jacobcline    schedule 30.04.2020    source แหล่งที่มา


คำตอบ (1)


ใช้ async/await และแพ็คเกจ express-async-wrap:

const wrap = require('express-async-wrap')
...
router.post('/', 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('/');
  }
}

person Anatoly    schedule 30.04.2020