ds9567 2016-06-01 05:58
浏览 55
已采纳

Golang Postgres错误常数?

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?

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

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?:

if err.ErrorCode != "xxx"

Thank you.

  • 写回答

1条回答 默认 最新

  • dongqiabei7682 2016-06-01 06:05
    关注

    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.

    This is how it can be done:

    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 has the following fields:

    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
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题