0

My golang main() routing initializes a db connection and then passes it to another function to start the main processing.

func main() {
    dbinfo := fmt.Sprintf("user=%s dbname=%s sslmode=disable", "my_user", "my_db")

    db, err := sql.Connect("postgres", dbinfo)
    if err != nil { log.Fatalln(err) }
    defer db.Close()


    model.Run(db)
}

The model.Run() method goes off to call several other packages and functions, and just passes the db object around between them.

What if one of those various downstream functions run into an error? Will the program just shut down without closing my connection defined above? Or will it bubble up the exception and execute my defer statement in main()?

For what it's worth, I'm handling all errors as follows -

_, err := someFunction()
if err != nil { log.Fatalln(err) }

Note: Fatalln is equivalent to calling Println and then os.Exit(1) (See here)

user2490003
  • 10,706
  • 17
  • 79
  • 155
  • Why not to do: `if err != nil { db.Close(); log.Fatalln(err) }`? – Alexander Trakhimenok Jun 01 '16 at 09:35
  • That would involve passing around the `db` object to every downstream function, whether it uses it or not, just so it could be used in the error call. I'm sure it would work! But I imagine there has to be a more efficient way – user2490003 Jun 01 '16 at 17:05
  • 1
    I probably would create some Context object that keeps DB and other staff and would be passing a pointer to it everywhere. Should not be costly. And why not just use `panic()`? You can recover and close connection. https://blog.golang.org/defer-panic-and-recover – Alexander Trakhimenok Jun 01 '16 at 23:25

0 Answers0