liveBook · Manning

Cause

As explained in Learn Go with Pocket-Sized Projects

context.Cause is a Go function that returns the specific cancellation cause associated with a context, or its usual cancellation error when none was set.

context.Cause(ctx) returns the specific error that caused a context to be canceled. Without an explicitly assigned cause, it returns the usual cancellation error. section 10.6.3

Use it when ctx.Err() is ambiguous. A context.WithTimeoutCause call may expire with context.DeadlineExceeded while carrying a more specific application error; context.Cause distinguishes the two. section 10.6.3

Choosing the cancellation diagnostic

When a remote or database operation exceeds its deadline, inspect context.Cause(ctx) rather than ctx.Err() to recover the configured cancellation cause. If no cause was configured, the result remains the usual cancellation error. section 10.6.3

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines fallback and explicit-cause behavior, but does not detail cause construction or broader cancellation internals.
Examples
Uses a WithTimeoutCause deadline scenario where ctx.Err() may hide the configured application error.
What it assumes
Assumes familiarity with Go contexts, cancellation, deadlines, ctx.Err(), and context.WithTimeoutCause.
What you can do after
Diagnose cancellation by selecting context.Cause(ctx) when ctx.Err() cannot identify the specific failure.
How it connects
Connects context.Context with context.WithTimeoutCause, ctx.Err(), deadlines, and cancellation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.