从Go中的PostgreSQL获取错误代码编号

huangapple go评论83阅读模式
英文:

Get error code number from postgres in Go

问题

我在获取Postgres错误时无法获取错误代码编号。

在我的程序测试中,我知道会出现以下错误:"pq: duplicate key value violates unique constraint "associations_pkey""。

根据Postgres文档,这很可能是一个pq错误代码为23505。

我需要在我的Go程序中获取该编号,以便可以检查不同类型的错误并以有帮助的方式响应给最终用户。

然而,我似乎无法在Go中获取错误代码,只能获取错误消息。我的代码如下:

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")
}
英文:

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")
}

答案1

得分: 17

你需要将错误断言为类型*pq.Error

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

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

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

答案2

得分: 13

这是文档中写的。如你所见,你可以通过以下方式提取它:

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

不要忘记从你的导入中删除下划线 _ "github.com/lib/pq"。如你所见,err 包含了关于错误的很多信息(不仅仅是 Code,还有其他很多信息)。

请注意,你不能直接将其与某个代码进行比较(它是 ErrorCode 类型)。

因此,你需要将其转换为字符串并与字符串进行比较。

英文:

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

huangapple
  • 本文由 发表于 2015年7月22日 22:06:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/31565505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定