从Go中的postgres获取错误代码号

从Go中的postgres获取错误代码号

问题描述:

I'm simply unable to retrieve the error code number when I get an error in postgres.

In the test of my program I know I'll get the following error " pq: duplicate key value violates unique constraint "associations_pkey"".

Looking in the postgres docs this is most likely an pq error code of 23505.

I need to get that number in my Go program so that I can check on different types of errors and respond to the end user in a helpful way.

However, I can't seem to get hold of the error code in Go, only the error message. My code is as follows:

stmt, _ := DB.Prepare("INSERT INTO table (column_1) VALUES ($1)")

_, err = stmt.Exec("12324354")

if err != nil {
    log.Println("Failed to stmt .Exec while trying to insert new association")
    log.Println(err.Error())
    fmt.Println(err.Code())

} else {
    Render.JSON(w, 200, "New row was created succesfully")
}

当我在postgres中遇到错误时,我根本无法检索错误代码号。 p>

在我的程序测试中,我知道会收到以下错误 “ pq:重复的键值违反了唯一约束” associations_pkey“”。 p>

在postgres文档中查找,这很可能是23505的pq错误代码。 p>

我需要在Go程序中获取该数字,以便检查不同类型的错误 并以有用的方式回应最终用户。 p>

但是,我似乎无法掌握Go中的错误代码,而只能获得错误消息。 我的代码如下: p>

  stmt,_:= DB.Prepare(“ INSERT INTO table(column_1)VALUES($ 1)”)
 
_,err = stmt  .Exec(“ 12324354”)
 
if err!= nil {
 log.Println(“尝试插入新关联时无法stmt .Exec”“ 
 log.Println(err.Error())
  fmt.Println(err.Code())
 
}其他{
 Render.JSON(w,200,“成功创建新行”)
} 
  code>  pre> 
   DIV>

You need to type assert the error to the type *pq.Error:

pqErr := err.(*pq.Error)
log.Println(pqErr.Code)

This is written in the documentation. As you see you can extract it in this way:

if err, ok := err.(*pq.Error); ok {
    fmt.Println(err.Code)
}

Do not forget to remove the underscore from your import _ "github.com/lib/pq". As you see err has a lot of information about the error (not only Code but many others).

Notice that you can't compare it directly to some code (it is of ErrorCode type).

So you have to convert it to string and compare against a string.

https://godoc.org/github.com/lib/pq#Error