Javascript 在哪里处理 sequelize ORM 查询语句中的错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35337738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:36:15  来源:igfitidea点击:

Where to handle the error in a sequelize ORM query statement?

javascriptexpresssequelize.js

提问by Josh Hale

I am using Sequelize ORM in Node/Express.

我在 Node/Express 中使用 Sequelize ORM。

I have two tables, User and Item. Item has a foreign key linked to UserId.

我有两个表,用户和项目。项目有一个链接到 UserId 的外键。

When I try to create an Item with a UserId that is invalid (not present in Users table) a "SequelizeForeignKeyConstraintError" is thrown and leads to crashing of the application due to unhandled.

当我尝试使用无效的 UserId(不存在于 Users 表中)创建一个项目时,会抛出“SequelizeForeignKeyConstraintError”并由于未处理而导致应用程序崩溃。

The problem I have is this:

我遇到的问题是:

Where do I handle the error?

我在哪里处理错误?

Here is my code.

这是我的代码。

.post(function(req,res){
        models.Item.create({
            title : req.body.title,
            UserId : req.body.UserId
        }).then(function(item){
            res.json({
                "Message" : "Created item.",
                "Item" : item
            });
        });
    });

回答by Jan Aagaard Meier

If you want to handle the specific error, attach a .catchhandler

如果要处理特定错误,请附加.catch处理程序

models.Item.create({
  title : req.body.title,
  UserId : req.body.UserId
}).then(function(item){
  res.json({
    "Message" : "Created item.",
    "Item" : item
  });
}).catch(function (err) {
  // handle error;
});

If you want to handle errors more generally (i.e. show a nice error message, instead of killing your server, you might want to have a look at unhandledexception

如果你想更一般地处理错误(即显示一个很好的错误消息,而不是杀死你的服务器,你可能想看看 unhandledexception

https://nodejs.org/api/process.html#process_event_uncaughtexception

https://nodejs.org/api/process.html#process_event_uncaughtexception

If you are using express, it also contains some error handling facilities http://expressjs.com/en/guide/error-handling.html

如果您使用 express,它还包含一些错误处理工具http://expressjs.com/en/guide/error-handling.html