[英]What is the proper way to handle Knex pg database errors
我正在使用带有 knex javascript 库的 postgres 来构建我的 sql 查询。 我想处理来自 postgres 服务器的所有抛出的错误,所以我想要这样做的方法是检查抛出的错误的类型。
try {
// knex query here
} catch(error) {
if(error instanceof DatabaseError) {
// handle pg error by checking error.code or something else
// then send an custom error message to the client
}
// handle another error here which is not caused by the postgres server
}
有没有办法处理这样的错误?
捕获 Knex/DB 错误:
您可以使用async
/ await
语法:
async function() {
try {
await knex(/* knex query here*/)
} catch(error) {
if(error instanceof DatabaseError) {
// handle pg error by checking error.code or something else
// then send an custom error message to the client
}Sorry
// handle another error here which is not caused by the postgres server
}
如果由于某种原因您不想使用该(较新的)语法,您也可以链接.catch
...
knex(/* knex query here*/)
.then(doWhatever)
.catch(error => {
if(error instanceof DatabaseError) { // ...
});
或者,您也可以使用 Knex 的查询错误( https://knexjs.org/#Interfaces-query-error )......但就我个人而言,我从来没有看到内置 promise 处理程序工作得很好。
(编辑)区分 PG 错误和 Knex 错误:
如果您想区分 Knex 和特定于 PG 的错误,您可以将错误处理程序直接连接到您的 PG 连接(绕过 Knex),如下所示:
function afterCreate(connection, callback) {
connection.on("error", connectionError);
callback(null, connection);
}
db.client.pool.config.afterCreate = afterCreate;
如果你这样做,你将不需要一个error instanceof DatabaseError
,因为connection.on
捕获的所有错误都将是 PG 错误。
您可能还会发现这个问题线程(我从中获得该代码)很有用: https://github.com/knex/knex/issues/522 ,因为它讨论了 Knex 中的错误处理,特别是底层数据库的处理错误。
(编辑)但是当我发现错误时如何区分它们?
不幸的是,我不认为 PG 错误没有独特的原型(即类)或其他显着特征。 您可以通过查看一个示例(来自我链接的那个线程)来看到这一点:
{"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","address":"127.0.0.1","port":5432}
如您所见,除非您开始检查特定功能,例如code === 'ECONNREFUSED'
(错误上没有isPg: true
标志),否则无法查看并知道“这是来自 PostgreSQL”。
为什么 Knex 不能智能地为我们识别数据库错误? 从同一个问题线程:
几乎不可能为 knex 创建像 redis 这样的事件,因为许多不同的数据库驱动程序实际上并不支持监听连接错误
-elhigu(Knex 团队成员)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.