【发布时间】:2021-07-19 11:35:49
【问题描述】:
我刚开始构建 API、node.js、postgres,所以这可能是一个有点幼稚的问题.. 我注意到,当我调用 update 方法并且没有找到记录时,该方法会引发错误,并且我期待一个空结果,我会发送一个 404 响应。我只是想知道这(从错误中返回响应)是否被认为是不好的做法,如果我不应该只执行两个查询,第一个是检查记录是否存在,第二个是更新它。 这是我的更新方法
exports.updateProductById = async (req, res) => {
const productId = parseInt(req.params.id);
const { productName, quantity, price, city, region, country } = req.body;
await db.one({
name: 'update-product',
text: 'UPDATE products SET productName = $1, quantity = $2, price = $3, city = $4, region = $5, country = $6 WHERE productId = $7 RETURNING productId, productName, quantity, price, city, region, country',
values: [productName, quantity, price, city, region, country, productId]
})
.then(result => {
console.log('update-product:', result);
if (result != null) {
res.status(200).send({
message: 'Product Updated Successfully!',
data: result
});
}
else {
// not called
res.status(404).send({
error: 'Product not found.'
});
}
})
.catch(error => {
console.log('update-product error:', error);
// workaround
res.status(404).send({
error: 'Product not found.'
});
});
};
【问题讨论】:
-
您实际上是在为整个 Promise 链设置一个包罗万象的错误处理程序。你确定这个承诺链将抛出的唯一实例是在未找到产品的情况下吗?此外,您将在这里处理失败的更新场景 - 在这种情况下,404 实际上是正确的 http 标头吗?
-
确实这不是它可能抛出的唯一错误..即传递给api的不可为空的参数..我想我应该设置一个用于错误处理/响应返回的开关。
-
所以没有得到一个空值而是一个错误,这是预期的行为吗?
-
我对 postgres api 了解不多,所以我不知道这是否应该是预期的行为。但这在某种程度上是有道理的,因为它可能认为这是更新操作的某种失败的先决条件。
标签: node.js postgresql pg-promise