Exceptions
When a token is cancelled, you can call the check() method on it and an exception will be raised:
from cantok import TimeoutToken
token = TimeoutToken(1)
token.wait()
token.check()
#> ...
#> cantok.errors.TimeoutCancellationError: The timeout of 1 second has expired.
Each type of token (except DefaultToken) has a corresponding type of exception that can be raised in this case:
SimpleToken->CancellationErrorConditionToken->ConditionCancellationErrorTimeoutToken->TimeoutCancellationErrorCounterToken->CounterCancellationError
When you call the check() method on any token, one of two things will happen. If it (or any of the tokens nested in it) has been cancelled by calling the cancel() method, CancellationError will always be raised. But if the cancellation occurred as a result of the unique ability of the token, such as timeout expiration for TimeoutToken, then an exception specific to this type of token will be raised.
ConditionCancellationError, TimeoutCancellationError, and CounterCancellationError are inherited from CancellationError, so if you're not sure which specific exception you're catching, catch CancellationError. All of the listed exceptions can also be imported separately:
from cantok import CancellationError, ConditionCancellationError, TimeoutCancellationError, CounterCancellationError
You can also choose not to import these exceptions at all. For each token class, the corresponding exception class is accessible as the exception attribute:
from cantok import TimeoutToken, CancellationError
token = TimeoutToken(0)
try:
token.check()
except CancellationError as e:
print(type(e) is TimeoutToken.exception) #> True
And each exception object has a token attribute indicating the specific token that was cancelled. This can be useful in situations where several tokens are nested in one another and you want to find out which one has been cancelled: