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

huangapple go评论88阅读模式
英文:

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)
    }
}

huangapple
  • 本文由 发表于 2023年3月10日 17:03:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75694076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定