Custom Integration: Catching API connection error in sensor.py

Hey Guys,
i stuck troubleshooting an issue and would like to ask for your help.

I am currently working on a new custom integration which is working so far very well.
(In short i will query an API of a device and populate some sensor values within HA)

I am using the skeleton of code provided in the documentation to update the sensor data within async_update_data(): in my sensor.py. I have created a seperate pypi package which is acting as client, querying the API and filling variables.

If the API is for example no longer available i currently see many exceptions in the logs (my pypi packages is raising a ValueError if the connection can not established) This exceptions are now spamming the logs

Following the best practices document quality scale i will try to catch this error, and log them only once in the log.

There is my code:

async def async_setup_entry(hass, entry, async_add_entities):
    """Config entry example."""

    async def async_update_data():

        def syncUpdate():

            try:
                varta = vartastorage.VartaStorage(
                    entry.data["host"], entry.data["port"]
                )
                varta.get_all_data()
                return varta
            except Exception as e:
                raise UpdateFailed("Error communicating with API")

        try:
            async with async_timeout.timeout(10):
                result = await hass.async_add_executor_job(syncUpdate)
                thisdict = {}
                # Filling the dict with all the data
                return thisdict
        except Exception as e:
            raise UpdateFailed("Error communicating with API")

However i still see the exceptions and the ValueErrors are not catched as expected. I also see that the code above is only hitted once after starting HA in my debugger.

Does you have an idea what i can try?

Hey all,
sorry for bother you. I found it:
The code above is correct. The root cause of the issue was within my pypi module i have imported

I used there the following code to raise an exception
traceback.print_exception(*sys.exc_info())

Those type of exceptions can’t be catched. After changing this to raise ValueError("errormsg") it now looks better :slight_smile: