droplets icon indicating copy to clipboard operation
droplets copied to clipboard

Use log.Print, not log.Fatal in the main

Open sofasurfa opened this issue 5 years ago • 2 comments
trafficstars

@spy16 Also I noticed that defer closeSession() wouldn't execute in the main. As Fatalf logs the error and then calls os.Exit(1).

defer closeSession()

if err := srv.ListenAndServe(); err != nil {
		lg.Fatalf("http server exited: %s", err) // os.Exit(1) doesn't care about defer
	}

I think it's better to do this

if err := srv.ListenAndServe(); err != nil {
		lg.Printf("http server exited: %s", err) // Print instead
}
defer os.Exit(1)
defer closeSession() // this executes first 

Another option would be to use panic() instead of lg.Fatalf() every where, and then at the bottom of main we could recover panics...

db, closeSession, err := mongo.Connect(cfg.MongoURI, true)
if err != nil {
  panic("failed to connect to mongodb: " + err)
}

// do the same for server and every where else
if err := srv.ListenAndServe(); err != nil {
		panic("http server exited: " + err)
}

// Recover all panics 
defer func() {
        if r := recover(); r != nil {
            closeSession()
            //.. add more clean ups here if needed (we have access to all the functions declared  higher)
            lg.Fatalf(r)  
          
        }
  }()

This methods creates a centralised place for our clean ups, but it does require to use panic for every error that occurs in the main. So it's not very clean, and it kind of goes against the purpose of panic... thus I think method 1 is better. What do you think?

sofasurfa avatar Oct 22 '20 10:10 sofasurfa

@spy16 Created a pull request #15

sofasurfa avatar Oct 27 '20 01:10 sofasurfa

Apologies for the delay and thanks for the PR. Left a comment on the PR. Do take a look and let me know your thoughts.

spy16 avatar Feb 21 '21 05:02 spy16