I am having trouble understanding how I can check if context exceeded deadline set by timeout, or if I should check at all?
This is a snippet from mongo-go-driver:
client, err := NewClient("mongodb://foo:bar@localhost:27017")
if err != nil { return err }
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil { return err }
Reading this code, how do I know if context exceeded deadline? From what I naively understand (or not understand), the line err = client.Connect(ctx)
will give me error including deadline exceeded (if exceeded), thus I think I don't even need to explicitly check?
But then while looking around the internet to better understand how contexts work, I come across uses of select cases which explicitly checks contexts as below (code snippet from http://p.agnihotry.com/post/understanding_the_context_package_in_golang/):
//Use a select statement to exit out if context expires
select {
case <-ctx.Done():
fmt.Println("sleepRandomContext: Time to return")
case sleeptime := <-sleeptimeChan:
//This case is selected when processing finishes before the context is cancelled
fmt.Println("Slept for ", sleeptime, "ms")
}
Should I be explicitly checking for it? If not, when should I use explicit checks? Thank you for your time and help!