What is the name of this error `update or delete on table "tablename" violates foreign key constraint` in GO?

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

What is the name of this error `update or delete on table "tablename" violates foreign key constraint` in GO?

问题

嗨,我正在使用GO中的database/sql包,并且我想处理这个错误,最好的方法是什么?

rows, err := transaction.Stmt(MypreparedStmt).Exec(id)
if err != nil {
    // 在这里,我想检查错误是否与外键有关,所以我想要类似以下的代码
    // if err == something {
    //     // 做一些操作
    // }
}
英文:

Hi I am using database/sql package in GO, and I want to handle this error,
what is the best way to do it?

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

答案1

得分: 5

很好的问题!我最好的猜测是这是一个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。将所有这些放在一起,看起来你可以这样做:

const foreignKeyViolationErrorCode = ErrorCode("23503")
if err != nil {
    if pgErr, isPGErr := err.(pq.Error); isPGErr {
        if pgErr.ErrorCode != foreignKeyViolationErrorCode {
            // 在这里处理foreign_key_violation错误
        }
    }
    // 处理非foreign_key_violation错误
}

**注意:**除了你想处理的那个之外,还可能有其他属于“外键违规”的错误情况。考虑探索pq.Error结构的其他字段,以缩小你感兴趣的特定错误情况。

英文:

Good question! My best guess is that this is a github.com/lib/pq.Error, but you can confirm this by pasting fmt.Printf("%T\n", err) at the error site. Going off this assumption, we can check the properties of this type:

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
}

Cool! Looks like we have an ErrorCode member. We can then check Postgres's error code list, where we find 23503 | foreign_key_violation. Putting all this together, it looks like you can do this:

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
}

NOTE: there may be other error conditions under the rubric of "foreign key violations" besides the one you're trying to handle. Consider exploring the other fields of the pq.Error struct to narrow in on the specific error case that interests you.

答案2

得分: 1

也许我没有理解你的问题,但从我理解的内容来看,你只是想测试错误是否与表中的外键列有关。那么为什么不找一个所有外键相关错误都有的常见“短语”,然后做如下处理:

import (
   //...
   "strings"
)

var foreignKeyError = "这里是一个在这类错误中总是出现的子字符串"

//...
if err != nil {

    if strings.Contains(err.Error(), foreignKeyError) {
        specialFunctionThatHandlesThisTypeOfError(err)
    } 

}

请注意,这只是一个示例代码,你需要根据实际情况修改foreignKeyErrorspecialFunctionThatHandlesThisTypeOfError以适应你的代码。

英文:

Maybe I'm not understanding your question but from what I get you simply want to test if the error has something to do with the foreign key column in your table. So why not find a common "phrase" that all the foreign key related errors have and do something like:

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

}

huangapple
  • 本文由 发表于 2016年11月3日 18:05:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/40398706.html
匿名

发表评论

匿名网友

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

确定