Add specialized exception for GATT Protocol Error
Discussed in https://github.com/hbldh/bleak/discussions/1772
Originally posted by PimWagemans09 May 29, 2025 currently if i get an error like bleak.exc.BleakError: Could not write value b'\x02' to characteristic 0011: Protocol Error 0x81: Unknown i just catch the error and print it but i want to get the error code "0x81" and process it is there any way to do this?
This is a specific case of #527.
Doing a read with response or a write can get specific errors from the peripheral device and Bleak users might want to handle specific error codes.
I'm pretty sure this is something that is available cross-platform, so we could make a BleakGattProtocolError exception that has a property containing the error code.
Hey was just curious as to how I can recreate this, plus is the formatting for these types of error roughly the same on all platforms, " Could not write value b'\x02' to characteristic 0011: Protocol Error 0x81: Unknown" where "Protocol Error 0x81" is always present?
was just curious as to how I can recreate this
Do you mean how to force hardware to generate and error? Just run the service explorer example and look for a characteristic that doesn't have the read property and try to read it or something like that.
is the formatting for these types of error roughly the same on all platforms
No, I would not expect so. On Windows, there is actually somewhat structured errors. If a GATT request fails, in the *Result, there is a Status and a ProtocolError (only if Status is ProtocolError).
So it would be nice to model a custom exception after that. I.e. the exception type should have properties to get the actual error numbers as integers so that users don't have to scrape it from a string.
On Linux/BlueZ, I don't think we have any choice but to scrape the string from the D-Bus error's extra data. On Mac, I don't know what sort of NSError we get and it isn't documented AFAICT, so we will probably just have to find a way to cause and error and see what happens.
The ProtocolError number should be the same cross-platform though because those numbers are defined by the Bluetooth spec. So we can add an enum for those.