3 回答

TA貢獻1821條經驗 獲得超5個贊
lib/pq包可能會返回類型*pq.Error為 struct 的錯誤。如果是這樣,您可以使用其所有字段來檢查錯誤的詳細信息。
這是可以做到的:
if err, ok := err.(*pq.Error); ok {
// Here err is of type *pq.Error, you may inspect all its fields, e.g.:
fmt.Println("pq error:", err.Code.Name())
}
pq.Error 具有以下字段:
type Error struct {
Severity string
Code ErrorCode
Message string
Detail string
Hint string
Position string
InternalPosition string
InternalQuery string
Where string
Schema string
Table string
Column string
DataTypeName string
Constraint string
File string
Line string
Routine string
}
這些字段的含義和可能的值是 Postres 特定的,完整列表可以在這里找到:錯誤和通知消息字段

TA貢獻1834條經驗 獲得超8個贊
你可以使用這個:https ://github.com/omeid/pgerror
它有很多針對各種 postgres 錯誤的映射。
使用該軟件包,您可以執行以下操作(摘自自述文件):
// example use:
_, err = stmt.Exec(SomeInsertStateMent, params...)
if err != nil {
if e := pgerror.UniqueViolation(err); e != nil {
// you can use e here to check the fields et al
return SomeThingAlreadyExists
}
return err // other cases.
}

TA貢獻1858條經驗 獲得超8個贊
這個包有所有的 PG 錯誤常量: https ://github.com/jackc/pgerrcode
只需導入即可:
import "github.com/jackc/pgerrcode"
// ...
if err, ok := err.(*pq.Error); ok {
if err.Code == pgerrcode.UniqueViolation {
return fmt.Errorf("unique field violation on column %s", err.Column)
}
}
該軟件包也屬于 2 或 3 個最流行的 Go PostgreSQL 驅動程序之一,稱為“pgx”,因此它應該足夠可靠。
- 3 回答
- 0 關注
- 326 瀏覽
添加回答
舉報