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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化