Skip to content

Commit b320a5c

Browse files
authored
added 23503 pgerrcode support and updated the error conversion approach (go-gorm#185)
* added 23503 pgerrcode support and updated the error conversion approach * updated to meaningful variables names
1 parent 5555b39 commit b320a5c

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

error_translator.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ import (
66
"gorm.io/gorm"
77
)
88

9-
var errCodes = map[string]string{
10-
"uniqueConstraint": "23505",
9+
var errDesToGormErrs = map[string]error{
10+
"23505": gorm.ErrDuplicatedKey,
11+
"23503": gorm.ErrForeignKeyViolated,
1112
}
1213

1314
type ErrMessage struct {
@@ -20,8 +21,9 @@ type ErrMessage struct {
2021
// 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.
2122
func (dialector Dialector) Translate(err error) error {
2223
if pgErr, ok := err.(*pgconn.PgError); ok {
23-
if pgErr.Code == errCodes["uniqueConstraint"] {
24-
return gorm.ErrDuplicatedKey
24+
gormErr, ok := errDesToGormErrs[pgErr.Code]
25+
if ok {
26+
return gormErr
2527
}
2628
return err
2729
}

0 commit comments

Comments
 (0)