context deadline exceeded
error occurs when using context.WithDeadline()
and the deadline has expired.
package main
import (
"context"
"log"
"time"
)
func main() {
var ctx context.Context
var ctxCancelFunc context.CancelFunc
var timeTillContextDeadline = time.Now().Add(3 * time.Second)
ctx, ctxCancelFunc = context.WithDeadline(context.Background(), timeTillContextDeadline)
defer ctxCancelFunc()
time.Sleep(5 * time.Second) //Sleep simulates time your program was doing something
//Check context for error, If ctx.Err() != nil gracefully exit the current execution
if ctx.Err() != nil {
log.Println(ctx.Err())
}
}
In most cases this isn’t an error you would fix. This is simple a signal that your code should stop and gracefully exit what its doing.
Created by Jon Calhoun, but you can check out the source and contribute on GitHub