{ (async (-6ren">
gpt4 book ai didi

javascript - 在 findByIdAndDelete 上处理 NodeJS DELETE 端点中的捕获

转载 作者:行者123 更新时间:2023-11-30 09:10:23 24 4
gpt4 key购买 nike

我正试图找到最好的方法来处理输出/响应中的捕获错误。

我有一条通过 ID 删除游戏的路线

router.delete("/delete/:id", (req, res) => {
(async () => {

try {
let deleteGame = await gameModel.findByIdAndDelete(ObjectId(req.params.id)).exec();

if (deleteGame === null) {
res.json({ error: `No game found with id ${req.params.id}` })
} else {
res.json({ message: `Game ${game.name} deleted` })
}

} catch (error) {
console.log(error)
}

})();
});

例如,当 ID 为非预期格式时,mongoose 将返回传入的参数必须是单个 12 字节的字符串或 24 个十六进制字符的字符串 in the "catch"

我不确定在 catch 中执行 res.json({ message: 'An error occurred' }) 是否是一个好习惯 - 这不是让服务器记录等.?

最佳答案

I am not sure if it a good practice to do res.json({ message: 'An error occured' }) in the catch - wouldn't that be for the server to log etc.?

那么,无论您是否在服务器上记录错误,您都需要向请求发送一些 响应。所以是的,从 catch 中调用 res.json 是有意义的。您返回的确切错误取决于您。 (根据您在 deleteGamenull 时所做的操作,您可能需要 error 而不是 message。)

关于javascript - 在 findByIdAndDelete 上处理 NodeJS DELETE 端点中的捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59590087/

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