24
loading...
This website collects cookies to deliver better user experience
ERROR #23505 duplicate key value violates unique constraint "users_username_key"
. Unfortunately, there is no validator involved here and pg
module returns most of the errors as map[byte]string
so this can be little tricky.func AddUser(user *User) error {
err = db.Model(user).Where("username = ?", user.Username).Select()
if err != nil {
return errors.New("Username already exists.")
}
...
}
pg
errors are mostly of type map[byte]string
, so for this particular error when you try to create user account with already existing username, you will get map on picture below:82 and 110
. Error type will be read from field 82
and we will extract column name from field 110
. Let's add these functions to internal/store/store.go
:func dbError(_err interface{}) error {
if _err == nil {
return nil
}
switch _err.(type) {
case pg.Error:
err := _err.(pg.Error)
switch err.Field(82) {
case "_bt_check_unique":
return errors.New(extractColumnName(err.Field(110)) + " already exists.")
}
case error:
err := _err.(error)
switch err.Error() {
case "pg: no rows in result set":
return errors.New("Not found.")
}
return err
}
return errors.New(fmt.Sprint(_err))
}
func extractColumnName(text string) string {
reg := regexp.MustCompile(`.+_(.+)_.+`)
if reg.MatchString(text) {
return strings.Title(reg.FindStringSubmatch(text)[1])
}
return "Unknown"
}
dbError()
function from internal/store/users.go
:func AddUser(user *User) error {
...
_, err = db.Model(user).Returning("*").Insert()
if err != nil {
log.Error().Err(err).Msg("Error inserting new user")
return dbError(err)
}
return nil
}