Golang postgres错误常数?

b0x*_*d1n 6 database postgresql go

我正在尝试使用postgres驱动程序(lib/pq)删除数据库,方法是:

db.Exec("DROP DATABASE dbName;")

但是我想根据收到的错误是奇怪的,还是"数据库不存在"错误来做一个不同的条件.

我的问题是,是否有一个常量变量或我可以用来检查返回的错误是否是"数据库不存在"错误消息,或者我是否必须自己手动解析错误字符串?

我试着查看文档,但找不到"数据库不存在"的任何内容.不过我找到了这个列表:https://www.postgresql.org/docs/9.3/static/errcodes-appendix.html

也许它适合其他一些错误代码?另外,我不太确定通过Postgres驱动程序获取和比较错误代码的语义正确方法.我认为我应该做这样的事情?:

if err.ErrorCode != "xxx"

谢谢.

icz*_*cza 14

所述lib/pq封装可以返回类型的错误*pq.Error,这是一个结构.如果是,您可以使用其所有字段来检查错误的详细信息.

这是如何做到的:

if err, ok := err.(*pq.Error); ok {
    // Here err is of type *pq.Error, you may inspect all its fields, e.g.:
    fmt.Println("pq error:", err.Code.Name())
}
Run Code Online (Sandbox Code Playgroud)

pq.Error 有以下字段:

type Error struct {
    Severity         string
    Code             ErrorCode
    Message          string
    Detail           string
    Hint             string
    Position         string
    InternalPosition string
    InternalQuery    string
    Where            string
    Schema           string
    Table            string
    Column           string
    DataTypeName     string
    Constraint       string
    File             string
    Line             string
    Routine          string
}
Run Code Online (Sandbox Code Playgroud)

这些字段的含义和可能值是Postres特定的,完整列表可以在这里找到:错误和通知消息字段