From c6ca36b411932dca29f55d4e0eb865715caf256c Mon Sep 17 00:00:00 2001 From: Noxx Date: Mon, 5 Jun 2023 20:59:24 +0200 Subject: [PATCH] Catch Redis exceptions while checking cache backend (#340) Exceptions thrown by Redis do not subclass builtin exceptions like ConnectionError. Prior to this commit such exceptions would not be catched while running the health-check on redis-backed cache backends. Co-authored-by: Markus Richter --- health_check/cache/backends.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/health_check/cache/backends.py b/health_check/cache/backends.py index c07d814e..02ddfc68 100644 --- a/health_check/cache/backends.py +++ b/health_check/cache/backends.py @@ -5,6 +5,19 @@ from health_check.exceptions import ServiceReturnedUnexpectedResult, ServiceUnavailable +try: + # Exceptions thrown by Redis do not subclass builtin exceptions like ConnectionError. + # Additionally, not only connection errors (ConnectionError -> RedisError) can be raised, + # but also errors for time-outs (TimeoutError -> RedisError) + # and if the backend is read-only (ReadOnlyError -> ResponseError -> RedisError). + # Since we know what we are trying to do here, we are not picky and catch the global exception RedisError. + from redis.exceptions import RedisError +except ModuleNotFoundError: + # In case Redis is not installed and another cache backend is used. + class RedisError(Exception): + pass + + class CacheBackend(BaseHealthCheckBackend): def __init__(self, backend="default"): super().__init__() @@ -27,5 +40,5 @@ def check_status(self): self.add_error(ServiceReturnedUnexpectedResult("Cache key warning"), e) except ValueError as e: self.add_error(ServiceReturnedUnexpectedResult("ValueError"), e) - except ConnectionError as e: + except (ConnectionError, RedisError) as e: self.add_error(ServiceReturnedUnexpectedResult("Connection Error"), e)