我想更新一个名为client的表。以下代码适用于有效 id,但对于无效 id,它只是挂起而不调用 catch 函数。
knex('client').where('id',id).update({
name:req.body.name
}).then(function(numberOfUpdatedRows) {
if(numberOfUpdatedRows) {
res.json(success);
return;
}
}).catch(function(err){
res.status('500');
res.json(err);
return;
});
});
我像这样解决了这个问题:
knex('client').where('id',id).select('id').then(function(id){
if(id) {
//update
}else {
//failed
}
}).catch(function(err){
console.log("select id do not exist");
res.send("do not exist");
});
对于这种情况,对于无效的 id,knex 没有调用 catch 函数,而是挂断,而是返回 id 的空值,我使用它进行错误检查。
我是初学者,确信有更好的方法可以做到这一点。
有人可以提出更好的方法吗?
此外,我在 knex 文档中找不到太多关于 knex 如何处理此类错误情况的信息。那么我在哪里可以找到这些信息,以便将来可以自己解决它们。谢谢。
一个很好的例子是这个
db("table")
.update({deleted_at: "now()"})
.where("column", "value");
如果您想了解更多信息,请查看以下内容:http://knexjs.org/#Builder-update
代码执行没有任何问题,这就是不执行catch
方法的原因。在更新时捕获未找到错误的巧妙方法是这样的
const {name} = req.body;
knex("client")
.update({name})
.where({id})
.then(rows => {
// the argument here as you stated
// describes the number of rows updated
// therefore if no row found no row will be updated
if (!rows){
return res.status(404).json({success:false});
}
return res.json({success:true});
})
.catch( e => res.status(500).json(e));
或者如果你喜欢一行
const {name} = req.body;
knex("client")
.update({name})
.where({id})
.then(u => res.status(!!u?200:404).json({success:!!u}))
.catch(e => res.status(500).json(e));
这样使用 knex
const {id,name} = req.body;
const subQuery = knex('client').select('id').where({id})
subQuery.then(response=>{
if(response.length>0){
subQuery.update({name})
.then(resp=>{
res.json('update done')
})
.catch(err=>{res.json(err)})
}
else{
res.json('update failed')
}
})
.catch(err=>{res.json(err)})
knex
.select('id')
.from('client')
.where('id', id)
.then(([row]) => {
if (!row) {
console.log("select id do not exist")
return res.send("do not exist")
}
return knex('client')
.update('name', req.body.name)
.where('id', row.id)
});
如果我已经知道该行可能不存在,我会将此视为应由代码处理的逻辑错误。