sequelize ORM 查询语句中的错误在哪里处理?
Where to handle the error in a sequelize ORM query statement?
我在 Node/Express 中使用 Sequelize ORM。
我有两个 table,用户和项目。项目有一个链接到 UserId 的外键。
当我尝试使用无效的 UserId(用户 table 中不存在)创建项目时,抛出 "SequelizeForeignKeyConstraintError" 并导致应用程序因未处理而崩溃。
我遇到的问题是:
在哪里处理错误?
这是我的代码。
.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
});
});
});
如果要处理特定错误,请附上 .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;
});
如果你想更普遍地处理错误(即显示一个很好的错误消息,而不是杀死你的服务器,你可能想看看 unhandledexception
https://nodejs.org/api/process.html#process_event_uncaughtexception
如果你使用的是express,它还包含一些错误处理工具http://expressjs.com/en/guide/error-handling.html
您可以处理所有 ORM 错误 return HTTP 500 状态和一些默认错误消息,方法如下
router.use((error, request, response, next) => {
response.status(error.status || 500).json({
status: 'error',
error: {
message: error.message || serverErrorMsg,
},
});
});
以上代码还允许您使用将发送到客户端的自定义消息抛出错误
我在 Node/Express 中使用 Sequelize ORM。
我有两个 table,用户和项目。项目有一个链接到 UserId 的外键。
当我尝试使用无效的 UserId(用户 table 中不存在)创建项目时,抛出 "SequelizeForeignKeyConstraintError" 并导致应用程序因未处理而崩溃。
我遇到的问题是:
在哪里处理错误?
这是我的代码。
.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
});
});
});
如果要处理特定错误,请附上 .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;
});
如果你想更普遍地处理错误(即显示一个很好的错误消息,而不是杀死你的服务器,你可能想看看 unhandledexception
https://nodejs.org/api/process.html#process_event_uncaughtexception
如果你使用的是express,它还包含一些错误处理工具http://expressjs.com/en/guide/error-handling.html
您可以处理所有 ORM 错误 return HTTP 500 状态和一些默认错误消息,方法如下
router.use((error, request, response, next) => {
response.status(error.status || 500).json({
status: 'error',
error: {
message: error.message || serverErrorMsg,
},
});
});
以上代码还允许您使用将发送到客户端的自定义消息抛出错误