I’m trying to insert some data into a Database with Go. Due to the nature of the data (large export from another tool), I hit sometimes some of my models constraints.
With the following Go code
_, err := db.Exec(query, params...)
if err != nil {
log.Print(err)
}
I simply get an output like that
2023/03/10 09:40:26 pq: insert or update on table "table" violates foreign key constraint "table_constraint"
exit status 1
When I do the same Insert from pgAdmin, I get the same error but also some DETAIL information.
DETAIL: Key (id)=(abc) is not present in table "table_2".
Is there a way to get this DETAIL information in Go as well? I checked the Documentation and couldn’t find anything, but maybe there is a way?
>Solution :
Generally the db driver that you’re using will have a custom error type. You can assert the err
value to this error type and then, depending on the driver’s implementation, you should be able to glean more details about the issue. For example, when using github.com/lib/pq
, you can assert to *pq.Error
and read its Detail
field:
_, err := db.Exec(query, params...)
if err != nil {
if e, ok := err.(*pq.Error); ok {
log.Print(e.Detail)
}
}