Skip to content

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

@sofasurfa

Description

@sofasurfa

@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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions