javascript - 如果出现 pg 错误,表示服务器关闭
问题描述
我有一个快速应用程序附加到 pg 数据库。我正在处理错误。我希望将 pg 错误消息发送到前端,以便用户知道为什么此表单没有发送。现在,如果我向这个端点发送违反我的数据库约束的信息,它会关闭我的服务器。
我认为这与我如何处理错误有关,但我是新手,对如何处理这个问题有点困惑。
这是我的代码:快速路线:
app.post('/api/inbox', inbox.createInbox)
创建收件箱功能:
const createInbox = (request, response) => {
const { name, email, body, tag, subject } = request.body
console.log("request body", request.body)
pool.query('INSERT INTO inbox (name, email, body, tag, subject ) VALUES ($1, $2, $3, $4, $5)', [name, email, body, tag, subject ], (error, results) => {
if (error) {
return console.error(err.message);
}
console.log("get to Success contact")
response.status(200).send(`Inbox Added`)
})
}
解决方案
FYI, your server was probably shutting down because you were referencing err.message
in console.error(err.message)
, but the variable name is error
, not err
.
You also need to send an error response back to the client. Every http request your server receives needs to send some type of response:
const createInbox = (request, response) => {
const { name, email, body, tag, subject } = request.body
console.log("request body", request.body)
pool.query('INSERT INTO inbox (name, email, body, tag, subject ) VALUES ($1, $2, $3, $4, $5)', [name, email, body, tag, subject ], (error, results) => {
if (error) {
console.error(error.message); // log correct variable
response.status(500).send(error.message); // send error response
return;
}
console.log("get to Success contact")
response.status(200).send(`Inbox Added`)
})
}
推荐阅读
- eclipse - 无法将 Spark 与 Eclipse 中的 Hortonworks Sandbox 连接
- image - 颤振不会在网络中显示图像
- android - 我无法从可绘制文件夹中插入图标
- python - 获取导致测试发现在 VSCode 中失败的 TypeError 的 Linenumber
- html - 图像在 chrome 和 firefox 上显示不同,使用 flexbox 调整大小
- swift - macOS Bundles 之间的双向数据交换 (swift)
- mapbox - 如何显示希伯来地图框?
- python - 如何使用 Python 将本地化时间戳转换为 UTC?
- python - 屈服于... in
- css - 多个媒体查询未按预期工作