FR: Subclassing exceptions to make them easier to catch
See original GitHub issueDescription
I’ve been writing a piece of code that’s getting … more complicated than it probably should, I guess. But I have gotten a little annoyed by one thing in particular: The difficulty in handling the exceptions I get from Bleak:
Logger.error(f"Bleak error encountered: {e} ({e.__class__.__name__})")
gives me lines in my log like:
Bleak error encountered: org.bluez.Error.Failed (BleakDBusError)
Bleak error encountered: Device with address 01:02:03:04:05:06 was not found. (BleakError)
Bleak error encountered: Not connected (BleakError)
etc.
The first one is maybe difficult to do anything about, okay. But I have to do a manual parsing of the contents in my except BleakError as e:
handler of the second two - and I think it would be more obvious if they were for example BleakDeviceNotFoundError and BleakNotConnectedError*.
So, the suggestion: Make some exception classes for the expected types of returns from the library, and use BleakError for the rest.
(Obviously I’d be willing to contribute the code as well, but I won’t start working on it if it’s against a project principle.)
For example:
- BleakNotConnectedException
- BleakDeviceNotFoundException
- BleakPairingFailedException (Maybe used for Unpair as well? Or a separate one.)
- BleakBluetoothDisabledException
- BleakNotificationsAlreadyStartedException / BleakNotificationsNeverStartedException (Maybe these are genuinely errors)
- BleakReadException (when reading a characteristic fails)
- BleakWriteException (when writing a characteristic fails)
*: Or indeed BleakDeviceNotFoundException, as it is really not considered an error in the classical sense - a device not being found? But that’s a different matter, and an issue with the Python naming conventions.
Issue Analytics
- State:
- Created 2 years ago
- Comments:13 (6 by maintainers)
How can we proceed here? For my use case also “device not found” is a expected exception for unpair operations. What do you think about starting with this exception and add other ones later on? DeviceNotFound should be easy to find and implement in all backends. Also NotConnected seems to be an easy and obvious one.
Just one one about
since https://github.com/hbldh/bleak/pull/522 this one usually also has description and can be further classified into above mentioned categories.