Skip to content

Fix/preserve original error in translate#335

Open
JonathanGunawan30 wants to merge 2 commits intogo-gorm:masterfrom
JonathanGunawan30:fix/preserve-original-error-in-translate
Open

Fix/preserve original error in translate#335
JonathanGunawan30 wants to merge 2 commits intogo-gorm:masterfrom
JonathanGunawan30:fix/preserve-original-error-in-translate

Conversation

@JonathanGunawan30
Copy link
Copy Markdown

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

Previously, Translate() discarded the original *pgconn.PgError and returned
only the sentinel error (e.g. gorm.ErrDuplicatedKey), breaking the error chain.

This fix wraps both errors using fmt.Errorf with multiple %w verbs (Go 1.20+),
so callers can still use errors.Is() for gorm error checking while also being
able to unwrap the original *pgconn.PgError via errors.As() to access details
like Detail, ConstraintName, etc.

User Case Description

Fixes #332

Before this fix:

errors.Is(err, gorm.ErrDuplicatedKey) // ✅ true
errors.As(err, &pgErr)                // ❌ false — original pgError is lost
pgErr.Detail                          // ❌ inaccessible

After this fix:

errors.Is(err, gorm.ErrDuplicatedKey) // ✅ true
errors.As(err, &pgErr)                // ✅ true
pgErr.Detail                          // ✅ "Key (email)=(foo@bar.com) already exists."
pgErr.ConstraintName                  // ✅ "users_email_key"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Dialector.Translate(error) omits original error message

1 participant