diff --git a/gorm.go b/gorm.go index 9a70c3d2..4402a2df 100644 --- a/gorm.go +++ b/gorm.go @@ -47,6 +47,8 @@ type Config struct { QueryFields bool // CreateBatchSize default create batch size CreateBatchSize int + // TranslateError enabling error translation + TranslateError bool // ClauseBuilders clause builder ClauseBuilders map[string]clause.ClauseBuilder @@ -348,8 +350,10 @@ func (db *DB) Callback() *callbacks { // AddError add error to db func (db *DB) AddError(err error) error { if err != nil { - if errTranslator, ok := db.Dialector.(ErrorTranslator); ok { - err = errTranslator.Translate(err) + if db.Config.TranslateError { + if errTranslator, ok := db.Dialector.(ErrorTranslator); ok { + err = errTranslator.Translate(err) + } } if db.Error == nil { diff --git a/tests/error_translator_test.go b/tests/error_translator_test.go index 2e472e34..ead26fce 100644 --- a/tests/error_translator_test.go +++ b/tests/error_translator_test.go @@ -9,10 +9,20 @@ import ( ) func TestDialectorWithErrorTranslatorSupport(t *testing.T) { + // it shouldn't translate error when the TranslateError flag is false translatedErr := errors.New("translated error") + untranslatedErr := errors.New("some random error") 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) { t.Fatalf("expected err: %v got err: %v", translatedErr, err) }