松鼠在错误信息中添加了“sql:”,导致错误处理时出现问题。

huangapple go评论88阅读模式
英文:

Squirrel appending "sql: " to errors, causing issues when error handling

问题

Golang项目:我正在使用Squirrel生成SQL查询,并使用pgx/stdlib作为Postgres驱动程序。我试图处理一个非常常见的错误,即ErrNoRows,基于我的一个查询,这是一个我想要优雅处理的可接受错误。问题是pgx返回的错误文本是“no rows in result set”,而Squirrel返回的是“sql: no rows in result set”,所以比较它们会失败。虽然文本相同,但Squirrel在错误前面加了前缀。处理这个问题的惯用方式是什么?我觉得截取或替换“sql: ”并不是合适的方式。

英文:

Golang project: I'm using Squirrel to generate SQL queries, and pgx/stdlib as a Postgres driver. I'm trying to account for a pretty common error, ErrNoRows, based on one of my queries, which is an acceptable error that I want to handle gracefully. The issue is pgx returns the error having text "no rows in result set", whereas Squirrel returns "sql: no rows in result set", so comparing them fails. Same text, just Squirrel is prefixing the error. What is the idiomatic way to handle this? I feel like substringing or replacing the "sql: " out isn't the appropriate way to go.

答案1

得分: 2

这是要翻译的内容:

不是database/sql在错误前面加上了"squirrel",而是database/sql对于sql.ErrNoRows的定义。

由于某种原因,pgxErrNoRows定义为errors.New("no rows in result set")

但是,由于它是公开的,你可以在应用程序启动时执行以下操作:

pgx.ErrNoRows = sql.ErrNoRows

或者编写一个函数:

func IsErrNoRows(err error) bool {
    return errors.Is(err, sql.ErrNoRows) || errors.Is(err, pgx.ErrNoRows)
}
英文:

It's not squirrel prefixing the error, that is what database/sql has for sql.ErrNoRows.

For some reason, pgx does ErrNoRows = errors.New("no rows in result set")

But, since it's exported, you could just do:

pgx.ErrNoRows = sql.ErrNoRows

when your application starts up. Or write a function

func IsErrNoRows(err error) bool {
    return errors.Is(err, sql.ErrNoRows) || errors.Is(err, pgx.ErrNoRows)
}

huangapple
  • 本文由 发表于 2021年5月29日 02:38:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/67744026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定