refactor: translatorError flag added for backward compatibility (#6178)

Co-authored-by: Saeid Saeidee <s.saeidee@sensysgatso.com>
This commit is contained in:
Saeid Kanishka 2023-03-24 03:07:05 +01:00 committed by GitHub
parent 5d1cdfef2e
commit b444011d09
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 3 deletions

View File

@ -47,6 +47,8 @@ type Config struct {
QueryFields bool QueryFields bool
// CreateBatchSize default create batch size // CreateBatchSize default create batch size
CreateBatchSize int CreateBatchSize int
// TranslateError enabling error translation
TranslateError bool
// ClauseBuilders clause builder // ClauseBuilders clause builder
ClauseBuilders map[string]clause.ClauseBuilder ClauseBuilders map[string]clause.ClauseBuilder
@ -348,8 +350,10 @@ func (db *DB) Callback() *callbacks {
// AddError add error to db // AddError add error to db
func (db *DB) AddError(err error) error { func (db *DB) AddError(err error) error {
if err != nil { if err != nil {
if errTranslator, ok := db.Dialector.(ErrorTranslator); ok { if db.Config.TranslateError {
err = errTranslator.Translate(err) if errTranslator, ok := db.Dialector.(ErrorTranslator); ok {
err = errTranslator.Translate(err)
}
} }
if db.Error == nil { if db.Error == nil {

View File

@ -9,10 +9,20 @@ import (
) )
func TestDialectorWithErrorTranslatorSupport(t *testing.T) { func TestDialectorWithErrorTranslatorSupport(t *testing.T) {
// it shouldn't translate error when the TranslateError flag is false
translatedErr := errors.New("translated error") translatedErr := errors.New("translated error")
untranslatedErr := errors.New("some random error")
db, _ := gorm.Open(tests.DummyDialector{TranslatedErr: translatedErr}) db, _ := gorm.Open(tests.DummyDialector{TranslatedErr: translatedErr})
err := db.AddError(errors.New("some random error")) err := db.AddError(untranslatedErr)
if errors.Is(err, translatedErr) {
t.Fatalf("expected err: %v got err: %v", translatedErr, err)
}
// it should translate error when the TranslateError flag is true
db, _ = gorm.Open(tests.DummyDialector{TranslatedErr: translatedErr}, &gorm.Config{TranslateError: true})
err = db.AddError(untranslatedErr)
if !errors.Is(err, translatedErr) { if !errors.Is(err, translatedErr) {
t.Fatalf("expected err: %v got err: %v", translatedErr, err) t.Fatalf("expected err: %v got err: %v", translatedErr, err)
} }