@@ -492,6 +492,13 @@ func (c *cancelCtx) cancel(removeFromParent bool, err, cause error) {
492
492
// Canceling this context releases resources associated with it, so code should
493
493
// call cancel as soon as the operations running in this Context complete.
494
494
func WithDeadline (parent Context , d time.Time ) (Context , CancelFunc ) {
495
+ return WithDeadlineCause (parent , d , nil )
496
+ }
497
+
498
+ // WithDeadlineCause behaves like WithDeadline but also sets the cause of the
499
+ // returned Context when the deadline is exceeded. The returned CancelFunc does
500
+ // not set the cause.
501
+ func WithDeadlineCause (parent Context , d time.Time , cause error ) (Context , CancelFunc ) {
495
502
if parent == nil {
496
503
panic ("cannot create context from nil parent" )
497
504
}
@@ -506,14 +513,14 @@ func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
506
513
propagateCancel (parent , c )
507
514
dur := time .Until (d )
508
515
if dur <= 0 {
509
- c .cancel (true , DeadlineExceeded , nil ) // deadline has already passed
516
+ c .cancel (true , DeadlineExceeded , cause ) // deadline has already passed
510
517
return c , func () { c .cancel (false , Canceled , nil ) }
511
518
}
512
519
c .mu .Lock ()
513
520
defer c .mu .Unlock ()
514
521
if c .err == nil {
515
522
c .timer = time .AfterFunc (dur , func () {
516
- c .cancel (true , DeadlineExceeded , nil )
523
+ c .cancel (true , DeadlineExceeded , cause )
517
524
})
518
525
}
519
526
return c , func () { c .cancel (true , Canceled , nil ) }
@@ -567,6 +574,13 @@ func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
567
574
return WithDeadline (parent , time .Now ().Add (timeout ))
568
575
}
569
576
577
+ // WithTimeoutCause behaves like WithTimeout but also sets the cause of the
578
+ // returned Context when the timout expires. The returned CancelFunc does
579
+ // not set the cause.
580
+ func WithTimeoutCause (parent Context , timeout time.Duration , cause error ) (Context , CancelFunc ) {
581
+ return WithDeadlineCause (parent , time .Now ().Add (timeout ), cause )
582
+ }
583
+
570
584
// WithValue returns a copy of parent in which the value associated with key is
571
585
// val.
572
586
//
0 commit comments