[英]Where to handle the error in a sequelize ORM query statement?
我在 Node/Express 中使用 Sequelize ORM。
我有兩個表,用戶和項目。 項目具有鏈接到 UserId 的外鍵。
當我嘗試使用無效的 UserId(不存在於用戶表中)創建項目時,會拋出“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 錯誤以返回 HTTP 500 狀態和一些默認錯誤消息
router.use((error, request, response, next) => {
response.status(error.status || 500).json({
status: 'error',
error: {
message: error.message || serverErrorMsg,
},
});
});
上面的代碼還允許您使用將發送給客戶端的自定義消息拋出錯誤,方法是將錯誤傳遞給next
函數
const error = new Error(/* your error message */);
error.status = 409;
next(error);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.