The context
package exports two variables:
Variables
var Canceled = errors.New("context canceled")
Canceled is the error returned by [Context.Err] when the context is canceled for some reason other than its deadline passing.
var DeadlineExceeded error = deadlineExceededError{}
DeadlineExceeded is the error returned by [Context.Err] when the context is canceled due to its deadline passing.
That’s it.
These are the only two types of errors that a context’s Err()
method is allowed to return.
It’s frequently useful to check against one or both of these error types when examining an error. As an example, when a database method returns context.Canceled
in the context of serving a web request, you may not want to log the error–it’s an indication that the client canceled the request before it was served, but you would want to log a context.DeadlineExceeded
error, because that means your database is taking too long.
err := db.Exec(ctx, /* ... some interesting query ... */)
switch {
case errors.Is(err, context.Canceled):
// Don't report the error to the caller, just return early
return nil
case err != nil:
// All other errors should be returned to the caller, for handling or logging,
// includding deadline exceeded errors.
return err
}
/* continue with other processing */