英文:
How can I get error details for a SQL Insert done in Go?
问题
我正在尝试使用Go将一些数据插入到数据库中。由于数据的性质(从另一个工具导出的大量数据),有时会遇到一些模型约束的问题。
使用以下Go代码:
_, err := db.Exec(query, params...)
if err != nil {
log.Print(err)
}
我只会得到如下输出:
2023/03/10 09:40:26 pq: insert or update on table "table" violates foreign key constraint "table_constraint"
exit status 1
当我使用pgAdmin进行相同的插入操作时,我会得到相同的错误,但还会有一些详细信息。
DETAIL: Key (id)=(abc) is not present in table "table_2".
在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
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?
答案1
得分: 2
通常,你使用的数据库驱动程序会有一个自定义的错误类型。你可以将err
值断言为这个错误类型,然后根据驱动程序的实现,你应该能够获取更多关于问题的详细信息。例如,当使用github.com/lib/pq
时,你可以断言为*pq.Error
,并读取其Detail
字段:
_, err := db.Exec(query, params...)
if err != nil {
if e, ok := err.(*pq.Error); ok {
log.Print(e.Detail)
}
}
英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论