Get error code number from postgres in Go
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
You need to type assert the error to the type *pq.Error
:
pqErr := err.(*pq.Error)
log.Println(pqErr.Code)