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
  1. 1cancel() function called before the operation finished
  2. 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)
Sources
Official documentation ↗

Go standard library

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Go errors