【问题标题】:Costum SQL Erros inside Try CatchTry Catch 中的自定义 SQL 错误
【发布时间】:2021-12-19 11:35:59
【问题描述】:

如何在 Try Catch 块中使用 SQL 错误。

try {
        const event = await Event.findByPk(event_id);
        if (!event) {
            throw Error("Event not found");
        }
        await Event.update({ name:name, date:date }, {
            where: {
            id: event.id
            }
        });
}
catch(error) {
        return res.status(400).json({status: "error", message: error.message});
}
    
return res.json({
        status: "success"
});

如果 Event.update 查询失败,会显示类似:

{
 "status": "error",
 "message": "column \"name\" does not exist"
}

我想展示这样的东西:

{
 "status": "error",
 "message": "Internal Server error"
}

【问题讨论】:

  • 在 catch 块中,将消息设置为您想要的值:return res.status(400).json({status: "error", message: "Internal Server Error"});

标签: javascript node.js error-handling try-catch


【解决方案1】:

这是你在 catch 块中应该有的。 catch 块中不需要'return':

    try {
            const event = await Event.findByPk(event_id);
            if (!event) {
                throw Error("Event not found");
            }
            await Event.update({ name:name, date:date }, {
                where: {
                id: event.id
                }
            });
    }
    catch(error) {
            res.status(400).send({status: "error", message: error});
    }

【讨论】:

  • 如果你没有返回你刚刚构建的错误响应,那么它将被丢弃,并执行以下返回成功响应的行。
猜你喜欢
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
  • 2021-09-08
  • 2017-03-27
  • 1970-01-01
相关资源
最近更新 更多