GORM Playground Link
https://github.com/go-gorm/playground/pull/649
Description
While creating a duplicate entry the error occured should be gorm.ErrDuplicateKey but its returning different error.
Comment From: twocs
I updated the error messaging to display the error itself. ` main_test.go:21: Error is not gorm.ErrDuplicateKey - Error 1062 (23000): Duplicate entry '1' for key 'users.PRIMARY'
In gorm.io, we don't use equality with errors, but errors.Is
Switch your error check to the following:
if errors.Is(res.Error, gorm.ErrDuplicatedKey) {
Furthermore, the error you see is returned by SQL dialect, so you cannot compare it directly with gorm errors without one extra step. The docs literally describe the exact issue you are experiencing: with ErrDuplicatedKey - https://gorm.io/docs/error_handling.html#Dialect-Translated-Errors
If you would like to be able to use the dialect translated errors(like ErrDuplicatedKey), then enable the TranslateError flag when opening a db connection.
db, err := gorm.Open(postgres.Open(postgresDSN), &gorm.Config{TranslateError: true})
I updated your db.go file to use this config
+ config := &gorm.Config{TranslateError: true}
...
52 db, err = gorm.Open(mysql.Open(dbDSN), config)
...
58 db, err = gorm.Open(postgres.Open(dbDSN), config)
...
69 db, err = gorm.Open(sqlserver.Open(dbDSN), config)`
...
72 db, err = gorm.Open(sqlite.Open(filepath.Join(os.TempDir(), "gorm.db")), config)
It works for me
> /workspaces/playground (master) $ GORM_DIALECT=sqlite go test
...
PASS
ok gorm.io/playground 0.034s
> /workspaces/playground (master) $ GORM_DIALECT=mysql go test
...
PASS
ok gorm.io/playground 4.041s
> /workspaces/playground (master) $ GORM_DIALECT=postgres go test
...
PASS
ok gorm.io/playground 0.438s
Comment From: NeerajGartia21
Oh sorry. I really missed that :). Thanks @twocs !!. It was really helpful.