Ответ
В Go 1.21 появились два новых метода контекста:
-
WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc)
АналогWithDeadline, но позволяет указать причину отмены, которая будет доступна черезcontext.Cause(). -
WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)
Аналогично, но для таймаута.
Пример:
ctx, cancel := context.WithTimeoutCause(
context.Background(),
time.Second,
errors.New("processing took too long"),
)
defer cancel()
// ...
if err := ctx.Err(); err != nil {
cause := context.Cause(ctx) // получим "processing took too long"
}