mirror of https://github.com/go-gorm/gorm.git
feat: Unique Constraint Violation error translator for different drivers (#6004)
* feat: duplicated key error translator for different drivers * test: removed the dependency * test: fixed broken tests * refactor: added ErrorTransltor interface * style: applied styler --------- Co-authored-by: Saeid Saeidee <s.saeidee@sensysgatso.com>
This commit is contained in:
parent
f3874339ef
commit
85eaf9eeda
|
@ -45,4 +45,6 @@ var (
|
|||
ErrInvalidValueOfLength = errors.New("invalid association values, length doesn't match")
|
||||
// ErrPreloadNotAllowed preload is not allowed when count is used
|
||||
ErrPreloadNotAllowed = errors.New("preload is not allowed when count is used")
|
||||
// ErrDuplicatedKey occurs when there is a unique key constraint violation
|
||||
ErrDuplicatedKey = errors.New("duplicated key not allowed")
|
||||
)
|
||||
|
|
4
gorm.go
4
gorm.go
|
@ -347,6 +347,10 @@ func (db *DB) Callback() *callbacks {
|
|||
|
||||
// AddError add error to db
|
||||
func (db *DB) AddError(err error) error {
|
||||
if errTranslator, ok := db.Dialector.(ErrorTranslator); ok {
|
||||
err = errTranslator.Translate(err)
|
||||
}
|
||||
|
||||
if db.Error == nil {
|
||||
db.Error = err
|
||||
} else if err != nil {
|
||||
|
|
|
@ -86,3 +86,7 @@ type Rows interface {
|
|||
Err() error
|
||||
Close() error
|
||||
}
|
||||
|
||||
type ErrorTranslator interface {
|
||||
Translate(err error) error
|
||||
}
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
package tests_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/utils/tests"
|
||||
)
|
||||
|
||||
func TestDialectorWithErrorTranslatorSupport(t *testing.T) {
|
||||
translatedErr := errors.New("translated error")
|
||||
db, _ := gorm.Open(tests.DummyDialector{TranslatedErr: translatedErr})
|
||||
|
||||
err := db.AddError(errors.New("some random error"))
|
||||
if !errors.Is(err, translatedErr) {
|
||||
t.Fatalf("expected err: %v got err: %v", translatedErr, err)
|
||||
}
|
||||
}
|
|
@ -8,7 +8,9 @@ import (
|
|||
"gorm.io/gorm/schema"
|
||||
)
|
||||
|
||||
type DummyDialector struct{}
|
||||
type DummyDialector struct {
|
||||
TranslatedErr error
|
||||
}
|
||||
|
||||
func (DummyDialector) Name() string {
|
||||
return "dummy"
|
||||
|
@ -92,3 +94,7 @@ func (DummyDialector) Explain(sql string, vars ...interface{}) string {
|
|||
func (DummyDialector) DataTypeOf(*schema.Field) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d DummyDialector) Translate(err error) error {
|
||||
return d.TranslatedErr
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue