We’ve seen that we can cancel contexts in a few ways–explicitly, or via timeouts. And that canceling a parent context also cancels all of its children.
But in all of these cases we get only two possible error values: context.Canceled
or context.DeadlineExceeded
. What if you wish to express additional details about a cancelation? This is where the concept of a ‘cause’ comes into play…
Overview
…
The WithCancelCause, WithDeadlineCause, and WithTimeoutCause functions return a CancelCauseFunc, which takes an error and records it as the cancellation cause. Calling Cause on the canceled context or any of its children retrieves the cause. If no cause is specified, Cause(ctx) returns the same value as ctx.Err().
These *Cause
variations of context cancelation allow you to provide an arbitrary error as the “cause” of the cancelation. This can then later be retrieved from the canceled context. Note that this “cause” error is still indepenent from the original context.Canceled
or context.DeadlineExceeded
error value. You must expressly check for the “cause” to get it. And we’ll talk more about how to do that, and the implications, when we get to those specific functions.