zac*_*rry 5 mysql node.js knex.js
我想更新一个名为 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;
});
});
Run Code Online (Sandbox Code Playgroud)
我这样解决了这个问题:
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");
});
Run Code Online (Sandbox Code Playgroud)
对于这种情况,对于无效的 id,knex 不会调用 catch 函数,而是不会挂起,而是返回 id 的空值,我用它来进行错误检查。
我是初学者,并且确信有更好的方法来做到这一点。
有人可以建议一种更好的方法吗?另外,我在knex 文档
中找不到太多有关 knex 如何处理此类错误情况的信息。那么我在哪里可以找到这些信息,以便以后我可以自己解决这些问题。谢谢。
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)
});
Run Code Online (Sandbox Code Playgroud)
如果我已经知道该行可能不存在,我会将其视为逻辑错误,应由代码处理。
| 归档时间: |
|
| 查看次数: |
49912 次 |
| 最近记录: |