Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I get error details for a SQL Insert done in Go?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading