context.Canceled
GoINFOCommonContext
context canceled
Quick Answer
Use errors.Is(err, context.Canceled) to detect cancellation and exit gracefully without logging.
What this means
Returned when a context is canceled via its cancel function before the operation completed. Normal in request lifecycles and should be checked, not always treated as an error.
Why it happens
- 1cancel() function called before the operation finished
- 2Parent context canceled propagating down to child contexts
Fix
Detect and return
Detect and return
if errors.Is(err, context.Canceled) {
return // caller canceled; not an error
}
log.Println("unexpected error:", err)Why this works
Distinguishing cancellation from real errors prevents noisy logs during normal shutdown.
Code examples
Detectgo
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := doWork(ctx)
if errors.Is(err, context.Canceled) {
fmt.Println("canceled")
}Select on donego
select {
case <-ctx.Done():
return ctx.Err()
case result := <-ch:
return result
}HTTP request with contextgo
req, _ := http.NewRequestWithContext(
ctx, "GET", url, nil)
http.DefaultClient.Do(req)Same error in other languages
Sources
Official documentation ↗
Go standard library
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev