gpt4 book ai didi

node.js - Sequelize - 如果外键值无效,请 try catch 不处理错误

转载 作者:行者123 更新时间:2023-12-03 22:25:24 48 4
gpt4 key购买 nike

我有一个 POST 路线来创建文档,在这条 route ,有一个条件,如果我收到一组标签,我会使用 Sequelize 在我创建多对多关系时提供的方法插入这些标签,在我的情况下, Sequelize 给了我 addTags。
我以这种方式发送 JSON 数据:

{
"description": "10000000000000",
"content": "conteudo1",
"groupId": 2,
"tags": [1,2,3,4]
}
id 为 1,2,3 的标签存在,但不存在 id 4,因此它应该抛出一个错误,该错误将被 try catch 捕获并传递给我的中间件,该中间件解析错误并返回其消息。

My code:

async create(req, res, next){
const { tags, ...data } = req.body

try {
const document = await Documents.create(data)
if(tags) {
document.addTags(tags)
}
return res.status(201).send()

} catch(error) { next(error) }

}
问题是 document.addTags(tags) 中生成的错误没有被捕获,所以即使有错误,它也会返回状态 201,而不是 500,这是在我的中间件中被调用的状态

The error:

(node:1856) UnhandledPromiseRejectionWarning: SequelizeForeignKeyConstraintError: insert or update on table "documentTags" violates foreign key constraint "documentTags_tagId_fkey"
at Query.formatError (C:\Users\arma_\OneDrive\Documentos\githubProjects\api-nodejs\node_modules\sequelize\lib\dialects\postgres\query.js:315:16)
at Query.run (C:\Users\arma_\OneDrive\Documentos\githubProjects\api-nodejs\node_modules\sequelize\lib\dialects\postgres\query.js:87:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:1856) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

最佳答案

由于 document.addTags(tags) 包含数据库操作。这些操作将以同步方式运行。也就是说,默认情况下,它将继续执行以下行而不等待其完成。
甚至在 document.addTags 完成之前 res.send() 就会被执行。
您可以使用 await 等待执行完成,也可以使用回调。

async create(req, res, next){
const { tags, ...data } = req.body

try {
const document = await Documents.create(data)
if(tags) {
await document.addTags(tags)
}
return res.status(201).send()

} catch(error) { next(error) }

}

关于node.js - Sequelize - 如果外键值无效,请 try catch 不处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63199663/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com