Get error code from postgres in Go

I just can't get the error code when I get the error in postgres.

In my program test, I know that I will get the following error "pq: Duplicate key value violates the unique association_pkey" constraint.

In postgres reports, this is most likely pq error code 23505.

I need to get this number in my Go program so that I can check for various types of errors and help the end user.

However, I can't seem to get the error code in Go, only the error message. My code looks like this:

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

      

+3


source to share


2 answers


You need to inject assert error into the type *pq.Error

:



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

      

+4


source


This is recorded in the documentation . As you can see, you can extract it like this:

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

      

Remember to remove the underline from your import _ "github.com/lib/pq"

. As you can see, it err

has a lot of information about the error (not only Code

, but many others).



Please note that you cannot compare it directly to some code (it matters ErrorCode type

).

So, you need to convert it to string and compare to string.

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

0


source







All Articles