【问题标题】:How to handle the sequelize unique constraint error?如何处理续集唯一约束错误?
【发布时间】:2021-09-28 12:50:45
【问题描述】:

我是 javascript 新手,我需要在 sequelize 中处理约束错误。我到处搜索与此主题相关的内容,但仍然无法获得适当的可行答案。我的尝试如下。

app.post('/api/users', (req, res) => {
  try {
    console.log(req.body);
    User.create(req.body)
        .then(user=> res.json(user));
  } catch (error) {
    console.log("Error: "+error);
  }});

这里还不能捕获异常。对于有效的用户输入,它能够发布请求。所以我只需要知道一种处理异常的方法。

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    正在四处寻找答案,但对给出的两个并不满意。如果您希望返回正确的响应,例如 403,这就是我想出的解决方案。

    app.post('/api/users', async (req, res) => {
        try {
            console.log(req.body);
            var user = await User.create(req.body)
            return res.status(200).json({ status: 'success', result: res.json(user) })
        } catch (error) {
            if (error.name === 'SequelizeUniqueConstraintError') {
                res.status(403)
                res.send({ status: 'error', message: "User already exists"});
            } else {
                res.status(500)
                res.send({ status: 'error', message: "Something went wrong"});
            }
        }
    });
    

    【讨论】:

      【解决方案2】:

      您可以将Promise.then().catch() 一起使用,或将async/awaittry/catch 一起使用

      这是Promise

      app.post('/api/users', (req, res) => {
          console.log(req.body);
          User.create(req.body)
              .then(user=> res.json(user))
              .catch(err => console.log(err))
      });
      

      这是async/await

      app.post('/api/users', async (req, res) => {
          try {
            console.log(req.body);
            const user = await User.create(req.body);
            res.json(user);
          } catch (error) {
            console.log("Error: "+error);
          }
      });
      

      【讨论】:

        【解决方案3】:

        看起来你正在混合两种不同的风格。如果您使用then(),则不需要try catch 块:

        app.post('/api/users', (req, res) => {
          console.log(req.body)
          User.create(req.body)
            .then(user => res.json(user))
            .catch(error => console.log('Error: ' + error))
        })
        

        另一种风格是使用async 包。使用异步,您的代码将如下所示:

        app.post('/api/users', async (req, res) => {
          console.log(req.body)
          try {
            const user = await User.create(req.body)
            res.json(user)
          }
          catch (error) { console.log('Error: ' + error) }
        })
        

        这两种方法都有它们的优点和缺点,超出了这个 sn-p 并且很多人会酌情使用这两种方法,例如 await 方法仅适用于使用 async 声明的函数内部,如第二个示例:@ 987654327@。在这种情况下,使用then() 风格的承诺处理是一种更好的方法

        【讨论】:

          猜你喜欢
          • 2018-11-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多