From 6e701ad1e036e5add96ed0d32e539b66b406bc00 Mon Sep 17 00:00:00 2001 From: Rataj Date: Sun, 6 Aug 2023 14:08:38 +0200 Subject: [PATCH] Fixed error message when dialector fails to initialize Let's say we have a problem with DSN which leads to dialector initialize error. However DB connection is not created and for some reason line 184 error provides even though "db" doesn't exist. Previously, this code leads to: panic: runtime error: invalid memory address or nil pointer dereference This fix now doesn't attempt to close non-existant database connection and instead continues, so the proper error is shown. In my case: [error] failed to initialize database, got error default addr for network 'localhost' unknown --- gorm.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gorm.go b/gorm.go index 203527af3..f106bf01e 100644 --- a/gorm.go +++ b/gorm.go @@ -181,7 +181,7 @@ func Open(dialector Dialector, opts ...Option) (db *DB, err error) { err = config.Dialector.Initialize(db) if err != nil { - if db, err := db.DB(); err == nil { + if db, _ := db.DB(); db != nil { _ = db.Close() } }