Skip to content

Commit

Permalink
Catch exceptions raised by TimezoneFinder.timezone_at (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
pnbruckner authored Apr 4, 2024
1 parent ffcfc95 commit 331d414
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
4 changes: 2 additions & 2 deletions custom_components/entity_tz/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Expand Down
17 changes: 16 additions & 1 deletion custom_components/entity_tz/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)

Expand Down

0 comments on commit 331d414

Please sign in to comment.