You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@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?
The text was updated successfully, but these errors were encountered:
@spy16 Also I noticed that
defer closeSession()
wouldn't execute in the main.As
Fatalf
logs the error and then callsos.Exit(1)
.I think it's better to do this
Another option would be to use
panic()
instead oflg.Fatalf()
every where, and then at the bottom of main we could recover panics...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?
The text was updated successfully, but these errors were encountered: