How to handle writing an entity properly

I have several custom integrations where I have entities which both read and write from a device over some form of connection. When this fails I would like the value to remain as it was, and the user to be made aware of the problem.

I’ll show a switch example:

    @property
    def is_on(self):
        """Return the state of the switch."""
        return self.coordinator.get_value(self._key)

    async def async_turn_on(self, **kwargs):
        await self.writeValue(1)

    async def async_turn_off(self, **kwargs):
        await self.writeValue(0)

    async def writeValue(self, value):
        """ Write value to device """
        try:
            await self.coordinator.write_value(self._key, value)
        finally:
            self.async_schedule_update_ha_state(force_refresh=False)

If this switch is set from off to on and fails, a UI error will pop up (because the command throws an exception). But the value in the UI will remain on, even though the value is really false. Calls to “is_on” will show it as false. A refresh of the page will also show it as false again.

I can also do like this:

    async def writeValue(self, value):
        """ Write value to device """
        try:
            await self.coordinator.write_value(self._key, value)
        except Exception as err:
            pass
        finally:
            self.async_schedule_update_ha_state(force_refresh=False)

Then there is no more an exception, and the value will display correctly. But I will no longer get the automatic exception message, which I would like to keep. Is there any good way to solve this?

An exception is not supposed to pass on to the frontend, so that is the actual proper way.
Obviously, instead of a plain pass, you should write an error message to the log, here.

Thanks for your reply, it confirms my suspicions. However, writing to the log file doesn’t really give a quick feedback to the user that something has gone wrong.

I haven’t looked into how the Home Assistant frontend works, is there any way I could manually create some kind of feedback to the client side “console / notification area”, replicating the error message?
Another nice solution could be to “flash” the entity with a red or green color depending on wheter the command succeeds or not.

Any suggestions would be very much appreciated!

Keep in mind that HA is not meant to be UI driven. If those errors are kind of “expected”, you could set an attribute and use automations to, e.g., send notifications