38
loading...
This website collects cookies to deliver better user experience
In this article, I will be using Go and lib/pq, but the same techniques also apply to most languages and drivers.
_, err = db.Exec("INSERT INTO users(email) VALUES($1)", "[email protected]")
// Check specifically for a unique constraint error
var pqErr *pq.Error
if errors.As(err, &pqErr) && pqErr.Code == "23505" {
// handle the violation
}
// Check if it was a different error
if err != nil {
panic(err)
}
_, err = db.Exec("INSERT INTO users(email) VALUES($1)", "[email protected]")
// Check specifically for a violation of the "unique_user_email" constraint
var pqErr *pq.Error
if errors.As(err, &pqErr) && pqErr.Constraint == "unique_user_email" {
// handle the violation
}
// Check if it was a different error
if err != nil {
panic(err)
}