Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get error code number from postgres in Go

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")
}
like image 738
Cyberlurk Avatar asked Jul 22 '15 14:07

Cyberlurk


2 Answers

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

pqErr := err.(*pq.Error)
log.Println(pqErr.Code)
like image 89
Ainar-G Avatar answered Nov 14 '22 03:11

Ainar-G


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

like image 32
Salvador Dali Avatar answered Nov 14 '22 03:11

Salvador Dali