mirror of https://github.com/go-gorm/gorm.git
refactor: translatorError flag added for backward compatibility (#6178)
Co-authored-by: Saeid Saeidee <s.saeidee@sensysgatso.com>
This commit is contained in:
parent
5d1cdfef2e
commit
b444011d09
4
gorm.go
4
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,9 +350,11 @@ func (db *DB) Callback() *callbacks {
|
|||
// AddError add error to db
|
||||
func (db *DB) AddError(err error) error {
|
||||
if err != nil {
|
||||
if db.Config.TranslateError {
|
||||
if errTranslator, ok := db.Dialector.(ErrorTranslator); ok {
|
||||
err = errTranslator.Translate(err)
|
||||
}
|
||||
}
|
||||
|
||||
if db.Error == nil {
|
||||
db.Error = err
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue