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

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

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源