What canceled my Go context?
a day ago
- #Debugging
- #Go
- #Context
- Go 1.20 introduced `WithCancelCause` and Go 1.21 added `WithTimeoutCause` to attach reasons to context cancellations.
- Traditional context cancellations only provide generic errors like `context canceled` or `context deadline exceeded`, lacking specific reasons.
- `WithCancelCause` allows attaching a custom error to context cancellation, improving debugging by providing specific failure reasons.
- `WithTimeoutCause` attaches a custom error when a timeout occurs, but `defer cancel()` on normal returns discards the custom cause.
- A manual timer pattern using `WithCancelCause` and `time.AfterFunc` ensures custom causes are preserved on all paths, including normal completion.
- For cases requiring `DeadlineExceeded` checks, stacking `WithCancelCause` on top of `WithTimeoutCause` preserves both custom causes and deadline semantics.
- Middleware can use `WithCancelCause` to log specific cancellation reasons, enhancing observability in client-server interactions.
- The cause APIs are increasingly adopted in the Go ecosystem, with libraries like `golang.org/x/sync/errgroup` and projects like Kubernetes leveraging them.