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.