From 331d4145494d1fb7d9c9762bcb91f095fb71580a Mon Sep 17 00:00:00 2001 From: Phil Bruckner Date: Thu, 4 Apr 2024 09:51:36 -0500 Subject: [PATCH] Catch exceptions raised by TimezoneFinder.timezone_at (#13) --- custom_components/entity_tz/__init__.py | 4 ++-- custom_components/entity_tz/helpers.py | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/custom_components/entity_tz/__init__.py b/custom_components/entity_tz/__init__.py index 40a03c1..74e14d1 100644 --- a/custom_components/entity_tz/__init__.py +++ b/custom_components/entity_tz/__init__.py @@ -63,8 +63,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: etzd.tz_users[entry.entry_id] = 0 loc_cache_size = len(etzd.loc_users) * LOC_CACHE_PER_CONFIG - _get_location._LRUCacheWrapper__maxsize = max( # type: ignore[attr-defined] # pylint: disable=protected-access - _get_location._LRUCacheWrapper__maxsize, # type: ignore[attr-defined] # pylint: disable=protected-access + _get_location._LRUCacheWrapper__maxsize = max( # pylint: disable=protected-access + _get_location._LRUCacheWrapper__maxsize, # pylint: disable=protected-access loc_cache_size, ) diff --git a/custom_components/entity_tz/helpers.py b/custom_components/entity_tz/helpers.py index 13a04e4..767d774 100644 --- a/custom_components/entity_tz/helpers.py +++ b/custom_components/entity_tz/helpers.py @@ -7,6 +7,7 @@ from enum import Enum, auto from functools import lru_cache import logging +import traceback from typing import Any, cast from zoneinfo import available_timezones @@ -74,13 +75,27 @@ def etz_data(hass: HomeAssistant) -> ETZData: return cast(ETZData, hass.data[DOMAIN]) +def format_exc(exc: Exception) -> str: + """Format an exception.""" + return "; ".join(s.strip() for s in traceback.format_exception_only(exc)) + + @lru_cache def _get_tz_from_loc(tzf: TimezoneFinder, lat: float, lng: float) -> tzinfo | None: """Get time zone from a location. This must be run in an executor since timezone_at may do file I/O. """ - if (tz_name := tzf.timezone_at(lat=lat, lng=lng)) is None: + try: + if (tz_name := tzf.timezone_at(lat=lat, lng=lng)) is None: + return None + except Exception as exc: # pylint: disable=broad-exception-caught + _LOGGER.debug( + "Getting time zone at (%f, %f) resulted in error: %s", + lat, + lng, + format_exc(exc), + ) return None return dt_util.get_time_zone(tz_name)