A context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context.
A context.Canceled
error does not necessarily mean a timeout error.
Scenario 1:
If you are using go routines, if the parent go routine finishes but child routine still runs in the background, and the child go routine had a context which is common to the parent go routine this can end up in a context cancelled, if the parent go routine cancels the context before exiting.
So if the child go routine does not have dependency on the parent's context, it is always a good practice to create a new context for background go routines. A new context can be created using the context.Background()
Scenario 2:
If your application is microservice based (or have several components which call each other using contexts), when microservice 1 calls microservice 2, and microservice 2 explicitly cancels the context, even in that case you can get this error.
A context can be canceled by calling the cancel()
function as shown below:
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
Cancelling this context releases resources associated with it. So if the callee has explicitly cancelled the context as shown above, this can result in a context.Canceled
error at caller.
These context cancelled errors can be handled checking the context.Canceled
error from a grpc.Dial()
call (if you are using grpc).