Said  Saifi
Said Saifi

Reputation: 2398

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

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

Upvotes: 1

Views: 1960

Answers (2)

weberc2
weberc2

Reputation: 7908

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.

Upvotes: 5

George H
George H

Reputation: 412

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

}

Upvotes: 1

Related Questions