Context Errors Classify With Errors Is

Classify context errors with errors.Is: canceled callers, exceeded deadlines, and healthy contexts each report a distinct outcome.

GoResilience

Code

snippet
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

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 ->`.