【问题标题】:What is the name of this error `update or delete on table "tablename" violates foreign key constraint` in GO?GO中这个错误“表“tablename”上的更新或删除违反外键约束”的名称是什么?
【发布时间】:2016-11-03 23:31:29
【问题描述】:

您好,我在 GO 中使用 database/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
    //}
}

【问题讨论】:

标签: sql postgresql go


【解决方案1】:

好问题!我最好的猜测是这是一个github.com/lib/pq.Error,但您可以通过在错误站点粘贴fmt.Printf("%T\n", err) 来确认这一点。抛开这个假设,我们可以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
}

酷!看起来我们有一个ErrorCode 成员。然后我们可以检查Postgres's error code list,我们在其中找到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 结构的其他字段,以缩小您感兴趣的特定错误案例。

【讨论】:

  • 感谢您的精彩回答。顺便说一句,我使用的是 golang 版本 1.13 和 pq lib 版本 v1.8.0。在这种情况下,我必须在您的解决方案中使用 err.(*pq.Error)pgErr.Code 才能使其正常工作。
  • 很高兴能帮上忙!
【解决方案2】:

也许我不理解您的问题,但据我所知,您只是想测试错误是否与表中的外键列有关。那么为什么不找到所有外键相关错误都有的通用“短语”并执行以下操作:

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

}

【讨论】:

  • 谢谢,但我希望能找到其他的东西
猜你喜欢
  • 2017-11-18
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 2019-11-05
  • 2018-05-17
  • 2020-02-07
  • 1970-01-01
相关资源
最近更新 更多