Golang postgres误差常数? [英] Golang postgres error constants?

查看:271
本文介绍了Golang postgres误差常数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用postgres驱动程序(lib / pq)删除数据库:

I'm trying to delete a database using the postgres driver (lib/pq) by doing a:

db.Exec DROP DATABASE dbName;)

但我想根据收到的错误是奇怪还是一个数据库不存在的错误。

But I'd like to do a different conditional based on whether the error received is something strange, or is a "database does not exist" error.

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

My question is, is there a constant variable or something I can use to check if the error returned is a "database does not exist" error message, or would I have to manually parse the error string myself?

我试图查看文档,但找不到任何存在。但我发现此列表: https://www.postgresql.org/ docs / 9.3 / static / errcodes-appendix.html

I tried to look in the documentation, but could not find anything for "database does not exist". I did however find this list: https://www.postgresql.org/docs/9.3/static/errcodes-appendix.html

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

Perhaps it fits under some other error code? Also I'm not quite sure the semantically correct way of fetching and comparing the error codes through the Postgres driver. I presume I should do something like this?:

如果err.ErrorCode!=xxx

谢谢。

推荐答案

lib / pq 包可能会返回类型 * pq.Error ,它是一个结构体。如果是,您可以使用它的所有字段检查错误的详细信息。

The lib/pq package may return errors of type *pq.Error, which is a struct. If it does, you may use all its fields to inspect for details of the 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())
}

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
}

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

The meaning and possible values of these fields are Postres specific and the full list can be found here: Error and Notice Message Fields

这篇关于Golang postgres误差常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆