Timeout Cause Explains Deadline Errors
WithTimeoutCause attaches a business reason to the deadline: ctx.Err stays DeadlineExceeded while context.Cause returns the specific cause for the failure.
Code
package main
import (
"context"
"errors"
"fmt"
"time"
)
func query(ctx context.Context) (string, error) {
select {
case <-time.After(200 * time.Millisecond): // 模拟慢查询
return "result", nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func main() {
// Go 1.21 的 WithTimeoutCause:超时那一刻 cause 进入取消链
ctx, cancel := context.WithTimeoutCause(
context.Background(),
50*time.Millisecond,
errors.New("upstream query too slow"),
)
defer cancel()
value, err := query(ctx)
if err != nil {
fmt.Println("err:", err)
fmt.Println("cause:", context.Cause(ctx))
return
}
fmt.Println("ok:", value)
}How the pieces connect
Timeout Cause Explains Deadline Errors is built around the functions query and main.
Failures are values here: 1 site check err and decide instead of letting one propagate. The function registers its cleanup up front with defer, so no exit path forgets it.
What to watch for
- Nothing to vet in a supply-chain review — the file pulls in no packages.
- Handle
errbefore the other return values; that ordering is the whole contract.
Applying it
Entry signature: func query(ctx context.Context) (string, error)
Running the file prints labeled results such as err:, cause:, ok: — each operation’s effect is visible in the output.
Treat main as the orchestrator calling query in a fixed order.
Statements that matter
func query(ctx context.Context) (string, error) {
select {
case <-time.After(200 * time.Millisecond): // 模拟慢查询
return "result", nil
case <-ctx.Done():
return "", ctx.Err()
}
}
if err != nil {
fmt.Println("err:", err)
fmt.Println("cause:", context.Cause(ctx))
return
}
ctx, cancel := context.WithTimeoutCause(
context.Background(),
50*time.Millisecond,
errors.New("upstream query too slow"),
)
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
- How should callers handle failures?
- Through `error` values, not panics — the snippet checks `err != nil` at 1 site.
- What does Timeout Cause Explains Deadline Errors print when run?
- The script runs standalone; its 3 labeled outputs include `err:`, `cause:`, `ok:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.