skip to content
Alvin Lucillo

Handle defer error in Go

/ 1 min read

💻 Tech

One common mistake in Go is not handling defer errors. Defer statement is included to perform operations before exiting a function. For example, closing a resource like DB pool. One may argue that the result of deferred function may not be important, or if it’s an error, it’s perfectly okay not to handle it. However, it doesn’t cultivate readability of code; someone new to the repository may think “Is this intentional?” or “Might this be a mistake or an imminent production bug?” A suggestion is to use a blank identifier. Even better, log it.

func (s svc) openDatabase(dsn string) (*DB, error) {
	db, err := s.connectDB(dsn)
	if err != nil {
		return nil, err
	}
	defer db.Close()

	/* Option 1 -- Ignoring with blank identifier
	defer func() {
		_ := db.Close()
	}()
	*/

	/* Option 2 -- Log it
	defer func() {
		err := db.Close()
		s.logger.Logf("Error closing the db: %v", err)
	}()
	*/

	return db, nil
}