Standard library / context

context.WithDeadlineCause()

Record a custom cause when the absolute deadline expires. Manual cancel does not set that custom cause. Expected stdout: 'context deadline exceeded budget\n'.

Formal Syntax & Structure

go syntaxgo
func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc)

Parameters & Attributes

NameTypeDescription
parentContextNon-nil parent context.
dtime.TimeAbsolute deadline.
causeerrorError to record when the specified deadline expires.

Return Value

(Context, CancelFunc)

Derived context and cancel function.

Working Example

Example Snippetgo
package main
import (  "context"  "errors"  "fmt"  "time")
func main() {  ctx, cancel := context.WithDeadlineCause(context.Background(), time.Now().Add(-time.Second), errors.New("budget"))  defer cancel()  <-ctx.Done()  fmt.Println(ctx.Err(), context.Cause(ctx))}
Go Reference