Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support for traslating error for pg driver #179

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions error_translator.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package postgres

import (
"encoding/json"
"github.com/jackc/pgx/v5/pgconn"
"gorm.io/gorm"
)
Expand All @@ -9,12 +10,35 @@ var errCodes = map[string]string{
"uniqueConstraint": "23505",
}

type ErrMessage struct {
Code string `json:"Code"`
Severity string `json:"Severity"`
Message string `json:"Message"`
}

// Translate it will translate the error to native gorm errors.
// 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
}
a631807682 marked this conversation as resolved.
Show resolved Hide resolved
return err
}

parsedErr, marshalErr := json.Marshal(err)
if marshalErr != nil {
return err
}

var errMsg ErrMessage
unmarshalErr := json.Unmarshal(parsedErr, &errMsg)
if unmarshalErr != nil {
return err
}

if errMsg.Code == errCodes["uniqueConstraint"] {
return gorm.ErrDuplicatedKey
}
return err
}