2 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個贊
至于 pq v1.5.2 和 gorm v1.9.12
首先,您需要確定創(chuàng)建方法調(diào)用是否返回錯誤。這樣
err := GetDB().Create(user).Error
if err != nil {
// code to handle error
}
然后pq包具有映射到postgres服務(wù)器錯誤的特殊類型。它包含可以幫助您識別錯誤嚴(yán)重性,代碼,與錯誤相關(guān)的表等字段。
psql 字段標(biāo)識符的完整列表可以在
錯誤和通知消息字段
https://www.postgresql.org/docs/current/protocol-error-fields.html
要解決您的問題作為一個選項(xiàng),我們可以使用字段
Code
這是錯誤代碼的字符串類型表示形式。但首先,我們需要強(qiáng)制轉(zhuǎn)換錯誤并檢查類型轉(zhuǎn)換是否成功。這樣
err := GetDB().Create(user).Error
if err != nil {
pqErr, ok := err.(pq.Error)
if !ok {
log.Fatal(err)
}
// code to handle specific error code
}
錯誤代碼列表可以在官方postgresql文檔中找到 https://www.postgresql.org/docs/9.3/errcodes-appendix.html
以及實(shí)際轉(zhuǎn)到pq庫中 github.com/lib/pq/error.go 的錯誤進(jìn)行pq特定映射
最后,我們可以通過代碼將錯誤處理為重復(fù)錯誤
err := GetDB().Create(user).Error
if err != nil {
pqErr, ok := err.(pq.Error)
if !ok {
log.Fatal(err)
}
// note that type casting here is redundant and used for showing specific
// string type from pq library
if pqErr.Code == pq.ErrorCode("23505") { // 23505 is unique_violation error code for psql
// now you can create error and write it to a message to return it for
// a client
}
}

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個贊
根據(jù)注釋,gorm 提供對“創(chuàng)建記錄”函數(shù)中數(shù)據(jù)庫錯誤的訪問,如下所示:
result := GetDB().Create(user)
if result.Error != nil {
// Do something with the error
}
請注意,檢查錯誤字符串可能會使您的應(yīng)用程序數(shù)據(jù)庫成為特定數(shù)據(jù)庫(但這可能不是您的問題)。這個問題的答案可能會提供進(jìn)一步的幫助。
- 2 回答
- 0 關(guān)注
- 89 瀏覽
添加回答
舉報(bào)