diff --git a/error_translator.go b/error_translator.go index 1f67d37..65fdc25 100644 --- a/error_translator.go +++ b/error_translator.go @@ -8,8 +8,9 @@ import ( "github.com/jackc/pgx/v5/pgconn" ) -var errCodes = map[string]string{ - "uniqueConstraint": "23505", +var errDesToGormErrs = map[string]error{ + "23505": gorm.ErrDuplicatedKey, + "23503": gorm.ErrForeignKeyViolated, } type ErrMessage struct { @@ -22,8 +23,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 } @@ -39,8 +41,9 @@ func (dialector Dialector) Translate(err error) error { return err } - if errMsg.Code == errCodes["uniqueConstraint"] { - return gorm.ErrDuplicatedKey - } + gormErr, ok := errDesToGormErrs[errMsg.Code] + if ok { + return gormErr + } return err } diff --git a/go.mod b/go.mod index 3a79ed1..24670c6 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.18 require ( github.com/jackc/pgx/v5 v5.3.1 - gorm.io/gorm v1.25.0 + gorm.io/gorm v1.25.1 ) require ( diff --git a/go.sum b/go.sum index bb7edd7..9ae2c58 100644 --- a/go.sum +++ b/go.sum @@ -23,5 +23,5 @@ golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gorm.io/gorm v1.25.0 h1:+KtYtb2roDz14EQe4bla8CbQlmb9dN3VejSai3lprfU= -gorm.io/gorm v1.25.0/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= +gorm.io/gorm v1.25.1 h1:nsSALe5Pr+cM3V1qwwQ7rOkw+6UeLrX5O4v3llhHa64= +gorm.io/gorm v1.25.1/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=