[英]What is the name of this error `update or delete on table “tablename” violates foreign key constraint` in GO?
嗨,我在GO中使用數據庫/ SQL包,我想處理此錯誤,最佳方法是什么?
rows, err := transaction.Stmt(MypreparedStmt).Exec(id)
if err!=nil{
// here I want to check if the error is something with the foreign key so I want something like
//if err==something{
//do something
//}
}
也許我不理解您的問題,但是從我得到的結果中,您只是想測試錯誤是否與表中的外鍵列有關。 那么,為什么不找到所有與外鍵相關的錯誤都有的常見“短語”,並執行類似的操作:
import (
//...
"string"
)
var foreignKeyError = "Here we have a substring that always appears in this type of errors"
//...
if err != nil {
if strings.Contains(err.Error(), foreignKeyError) {
specialFunctionThatHandlesThisTypeOfError(err)
}
}
好問題! 我最好的猜測是這是github.com/lib/pq.Error
,但是您可以通過在錯誤站點粘貼fmt.Printf("%T\\n", err)
來確認。 按照這個假設,我們可以檢查這種類型的屬性 :
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
}
涼! 看起來我們有一個ErrorCode
成員。 然后,我們可以檢查Postgres的錯誤代碼列表 ,在其中找到23503 | foreign_key_violation
23503 | foreign_key_violation
。 將所有這些放在一起,看來您可以執行以下操作:
const foreignKeyViolationErrorCode = ErrorCode("23503")
if err != nil {
if pgErr, isPGErr := err.(pq.Error); isPGErr {
if pgErr.ErrorCode != foreignKeyViolationErrorCode {
// handle foreign_key_violation errors here
}
}
// handle non-foreign_key_violation errors
}
注意:在“外鍵違規”的標題下,除您要處理的錯誤外,還可能存在其他錯誤情況。 考慮研究pq.Error
結構的其他字段,以縮小您感興趣的特定錯誤情況的范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.