Context Errors Classify With Errors Is
Classify context errors with errors.Is: canceled callers, exceeded deadlines, and healthy contexts each report a distinct outcome.
Code
package main
import (
"context"
"errors"
"fmt"
"time"
)
func classify(err error) string {
switch {
case errors.Is(err, context.Canceled):
return "caller gave up"
case errors.Is(err, context.DeadlineExceeded):
return "deadline ran out"
case err == nil:
return "no error"
default:
return "unexpected: " + err.Error()
}
}
func main() {
cancelled, cancel := context.WithCancel(context.Background())
cancel() // cancel immediately to force the canceled branch
// a deadline already in the past finishes the context at once
expired, expire := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer expire()
fmt.Println("cancel ->", classify(cancelled.Err()))
fmt.Println("deadline ->", classify(expired.Err()))
fmt.Println("healthy ->", classify(context.Background().Err()))
}What this snippet actually does — Context Errors Classify With Errors Is
Context Errors Classify With Errors Is comes down to the functions classify and main.
Cleanup is attached with defer, so it runs on every exit path of the function.
What to watch for
- No packages to fetch here: the language’s own built-ins cover every call the file makes.
Using it
Signature: func classify(err error) string
The demo output is labeled (cancel ->, deadline ->, healthy ->); each label names the call that printed it.
Running the file executes main, which drives classify in order.
Key statements
func classify(err error) string {
switch {
case errors.Is(err, context.Canceled):
return "caller gave up"
case errors.Is(err, context.DeadlineExceeded):
return "deadline ran out"
case err == nil:
return "no error"
default:
return "unexpected: " + err.Error()
}
}
expired, expire := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
cancelled, cancel := context.WithCancel(context.Background())
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Context Errors Classify With Errors Is print when run?
- Running the file directly is enough — expect labeled output lines such as `cancel ->`, `deadline ->`, `healthy ->`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.