Skip to content

Commit

Permalink
added 23503 pgerrcode support and updated the error conversion approa…
Browse files Browse the repository at this point in the history
…ch (#185)

* added 23503 pgerrcode support and updated the error conversion approach

* updated to meaningful variables names
  • Loading branch information
amirejaz75 committed May 19, 2023
1 parent 5555b39 commit b320a5c
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions error_translator.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import (
"gorm.io/gorm"
)

var errCodes = map[string]string{
"uniqueConstraint": "23505",
var errDesToGormErrs = map[string]error{
"23505": gorm.ErrDuplicatedKey,
"23503": gorm.ErrForeignKeyViolated,
}

type ErrMessage struct {
Expand All @@ -20,8 +21,9 @@ type ErrMessage struct {
// Since currently gorm supporting both pgx and pg drivers, only checking for pgx PgError types is not enough for translating errors, so we have additional error json marshal fallback.
func (dialector Dialector) Translate(err error) error {
if pgErr, ok := err.(*pgconn.PgError); ok {
if pgErr.Code == errCodes["uniqueConstraint"] {
return gorm.ErrDuplicatedKey
gormErr, ok := errDesToGormErrs[pgErr.Code]
if ok {
return gormErr
}
return err
}
Expand Down

0 comments on commit b320a5c

Please sign in to comment.