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
// 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 {

View File

@ -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)
}