Hamid
Hamid

Reputation: 593

How to get the duplicated field name in golang/gorm when postgress returns "duplicate key value violates unique constraint"?

I'm using golang gorm as database connector and almost everything is fine. here is the code for creating a new user (only the database part)

err = db.Create(&u).Error
if err != nil {
    postError(w, http.StatusInternalServerError, "internal server the fronterror!!", nil)
}

and when I try to add a user with a used email, this error happens:

ERROR: duplicate key value violates unique constraint "idx_users_email" (SQLSTATE 23505)

the problem is that gorm error handling page didn't help me that much to be able to get the error in a proper way and send a proper error code and message as response.

so what I want is to get the error and the name of the duplicated field ( in this case "email" ) and respond with a proper message/code instead of "500 internal server error" that I already send it in all error cases.

any help would be appreciated

Upvotes: 0

Views: 2127

Answers (1)

Peter
Peter

Reputation: 31720

Postgres doesn't return "the field" so GORM can't tell you either. The reason is that you are not violating a unique field, but a unique constraint. Constraints can refer to multiple columns, or complex expressions (consider CREATE UNIQUE INDEX i ON t (LOWER(id)).

The best you can do is map the name of the violated constraint to a nice user facing error message. How to do that depends on the database driver. For instance, github.com/lib/pq reports the name of the constraint directly in the error value:

type Error struct {
    Code             ErrorCode // "23505"
    Constraint       string    // "idx_users_email"

    // more fields
}

Upvotes: 1

Related Questions