Always log exception using logging.exception

This commit is contained in:
Josh Wu
2025-08-18 15:38:43 +08:00
parent 3b8dd6f3cf
commit 4a88e9a0cf
16 changed files with 65 additions and 74 deletions

View File

@@ -230,8 +230,8 @@ class SoundDeviceAudioOutput(ThreadedAudioOutput):
try: try:
self._stream.write(pcm_samples) self._stream.write(pcm_samples)
except Exception as error: except Exception:
print(f'Sound device error: {error}') logger.exception('Sound device error')
raise raise
def _close(self): def _close(self):

View File

@@ -137,8 +137,8 @@ class MessageAssembler:
self.pid, self.pid,
self.payload, self.payload,
) )
except Exception as error: except Exception:
logger.exception(color(f"!!! exception in callback: {error}", "red")) logger.exception(color("!!! exception in callback", "red"))
self.reset() self.reset()

View File

@@ -434,8 +434,8 @@ class MessageAssembler:
) )
try: try:
self.callback(self.transaction_label, message) self.callback(self.transaction_label, message)
except Exception as error: except Exception:
logger.exception(color(f'!!! exception in callback: {error}', 'red')) logger.exception(color('!!! exception in callback', 'red'))
self.reset() self.reset()
@@ -1400,10 +1400,8 @@ class Protocol(utils.EventEmitter):
try: try:
response = handler(message) response = handler(message)
self.send_message(transaction_label, response) self.send_message(transaction_label, response)
except Exception as error: except Exception:
logger.warning( logger.exception(color("!!! Exception in handler:", "red"))
f'{color("!!! Exception in handler:", "red")} {error}'
)
else: else:
logger.warning('unhandled command') logger.warning('unhandled command')
else: else:

View File

@@ -267,8 +267,8 @@ class PduAssembler:
assert self.pdu_id is not None assert self.pdu_id is not None
try: try:
self.callback(self.pdu_id, self.parameter) self.callback(self.pdu_id, self.parameter)
except Exception as error: except Exception:
logger.exception(color(f'!!! exception in callback: {error}', 'red')) logger.exception(color('!!! exception in callback', 'red'))
self.reset() self.reset()

View File

@@ -3242,8 +3242,8 @@ class Device(utils.CompositeEventEmitter):
else 0 else 0
) )
await advertising_set.start(duration=duration) await advertising_set.start(duration=duration)
except Exception as error: except Exception:
logger.exception(f'failed to start advertising set: {error}') logger.exception('failed to start advertising set')
await advertising_set.remove() await advertising_set.remove()
raise raise
@@ -4607,8 +4607,8 @@ class Device(utils.CompositeEventEmitter):
try: try:
await self.keystore.update(address, keys) await self.keystore.update(address, keys)
await self.refresh_resolving_list() await self.refresh_resolving_list()
except Exception as error: except Exception:
logger.warning(f'!!! error while storing keys: {error}') logger.exception('!!! error while storing keys')
else: else:
self.emit(self.EVENT_KEY_STORE_UPDATE) self.emit(self.EVENT_KEY_STORE_UPDATE)
@@ -5856,8 +5856,8 @@ class Device(utils.CompositeEventEmitter):
) )
) )
return return
except Exception as error: except Exception:
logger.warning(f'exception while confirming: {error}') logger.exception('exception while confirming')
await self.host.send_command( await self.host.send_command(
hci.HCI_User_Confirmation_Request_Negative_Reply_Command( hci.HCI_User_Confirmation_Request_Negative_Reply_Command(
@@ -5886,8 +5886,8 @@ class Device(utils.CompositeEventEmitter):
) )
) )
return return
except Exception as error: except Exception:
logger.warning(f'exception while asking for pass-key: {error}') logger.exception('exception while asking for pass-key')
await self.host.send_command( await self.host.send_command(
hci.HCI_User_Passkey_Request_Negative_Reply_Command( hci.HCI_User_Passkey_Request_Negative_Reply_Command(

View File

@@ -507,15 +507,15 @@ class Server(utils.EventEmitter):
error_code=error.error_code, error_code=error.error_code,
) )
self.send_response(connection, response) self.send_response(connection, response)
except Exception as error: except Exception:
logger.warning(f'{color("!!! Exception in handler:", "red")} {error}') logger.exception(color("!!! Exception in handler:", "red"))
response = att.ATT_Error_Response( response = att.ATT_Error_Response(
request_opcode_in_error=att_pdu.op_code, request_opcode_in_error=att_pdu.op_code,
attribute_handle_in_error=0x0000, attribute_handle_in_error=0x0000,
error_code=att.ATT_UNLIKELY_ERROR_ERROR, error_code=att.ATT_UNLIKELY_ERROR_ERROR,
) )
self.send_response(connection, response) self.send_response(connection, response)
raise error raise
else: else:
# No specific handler registered # No specific handler registered
if att_pdu.op_code in att.ATT_REQUESTS: if att_pdu.op_code in att.ATT_REQUESTS:
@@ -982,8 +982,8 @@ class Server(utils.EventEmitter):
# Accept the value # Accept the value
try: try:
await attribute.write_value(connection, request.attribute_value) await attribute.write_value(connection, request.attribute_value)
except Exception as error: except Exception:
logger.exception(f'!!! ignoring exception: {error}') logger.exception('!!! ignoring exception')
def on_att_handle_value_confirmation( def on_att_handle_value_confirmation(
self, self,

View File

@@ -707,11 +707,9 @@ class Host(utils.EventEmitter):
raise hci.HCI_Error(status) raise hci.HCI_Error(status)
return response return response
except Exception as error: except Exception:
logger.exception( logger.exception(color("!!! Exception while sending command:", "red"))
f'{color("!!! Exception while sending command:", "red")} {error}' raise
)
raise error
finally: finally:
self.pending_command = None self.pending_command = None
self.pending_response = None self.pending_response = None

View File

@@ -1695,8 +1695,8 @@ class ChannelManager:
if handler: if handler:
try: try:
handler(connection, cid, control_frame) handler(connection, cid, control_frame)
except Exception as error: except Exception:
logger.warning(f'{color("!!! Exception in handler:", "red")} {error}') logger.exception(color("!!! Exception in handler:", "red"))
self.send_control_frame( self.send_control_frame(
connection, connection,
cid, cid,
@@ -1706,7 +1706,7 @@ class ChannelManager:
data=b'', data=b'',
), ),
) )
raise error raise
else: else:
logger.error(color('Channel Manager command not handled???', 'red')) logger.error(color('Channel Manager command not handled???', 'red'))
self.send_control_frame( self.send_control_frame(
@@ -2192,8 +2192,8 @@ class ChannelManager:
# Connect # Connect
try: try:
await channel.connect() await channel.connect()
except Exception as error: except Exception:
logger.warning(f'connection failed: {error}') logger.exception('connection failed')
del connection_channels[source_cid] del connection_channels[source_cid]
raise raise

View File

@@ -1047,8 +1047,8 @@ class Client:
self.l2cap_channel = await self.connection.create_l2cap_channel( self.l2cap_channel = await self.connection.create_l2cap_channel(
spec=l2cap.ClassicChannelSpec(psm=RFCOMM_PSM, mtu=self.l2cap_mtu) spec=l2cap.ClassicChannelSpec(psm=RFCOMM_PSM, mtu=self.l2cap_mtu)
) )
except ProtocolError as error: except ProtocolError:
logger.warning(f'L2CAP connection failed: {error}') logger.exception('L2CAP connection failed')
raise raise
assert self.l2cap_channel is not None assert self.l2cap_channel is not None

View File

@@ -1084,8 +1084,8 @@ class Server:
def on_pdu(self, pdu): def on_pdu(self, pdu):
try: try:
sdp_pdu = SDP_PDU.from_bytes(pdu) sdp_pdu = SDP_PDU.from_bytes(pdu)
except Exception as error: except Exception:
logger.warning(color(f'failed to parse SDP Request PDU: {error}', 'red')) logger.exception(color('failed to parse SDP Request PDU', 'red'))
self.send_response( self.send_response(
SDP_ErrorResponse( SDP_ErrorResponse(
transaction_id=0, error_code=SDP_INVALID_REQUEST_SYNTAX_ERROR transaction_id=0, error_code=SDP_INVALID_REQUEST_SYNTAX_ERROR
@@ -1100,8 +1100,8 @@ class Server:
if handler: if handler:
try: try:
handler(sdp_pdu) handler(sdp_pdu)
except Exception as error: except Exception:
logger.exception(f'{color("!!! Exception in handler:", "red")} {error}') logger.exception(color("!!! Exception in handler:", "red"))
self.send_response( self.send_response(
SDP_ErrorResponse( SDP_ErrorResponse(
transaction_id=sdp_pdu.transaction_id, transaction_id=sdp_pdu.transaction_id,

View File

@@ -882,8 +882,8 @@ class Session:
if response: if response:
next_steps() next_steps()
return return
except Exception as error: except Exception:
logger.warning(f'exception while confirm: {error}') logger.exception('exception while confirm')
self.send_pairing_failed(SMP_CONFIRM_VALUE_FAILED_ERROR) self.send_pairing_failed(SMP_CONFIRM_VALUE_FAILED_ERROR)
@@ -901,8 +901,8 @@ class Session:
if response: if response:
next_steps() next_steps()
return return
except Exception as error: except Exception:
logger.warning(f'exception while prompting: {error}') logger.exception('exception while prompting')
self.send_pairing_failed(SMP_CONFIRM_VALUE_FAILED_ERROR) self.send_pairing_failed(SMP_CONFIRM_VALUE_FAILED_ERROR)
@@ -919,8 +919,8 @@ class Session:
return return
logger.debug(f'user input: {passkey}') logger.debug(f'user input: {passkey}')
next_steps(passkey) next_steps(passkey)
except Exception as error: except Exception:
logger.warning(f'exception while prompting: {error}') logger.exception('exception while prompting')
self.send_pairing_failed(SMP_PASSKEY_ENTRY_FAILED_ERROR) self.send_pairing_failed(SMP_PASSKEY_ENTRY_FAILED_ERROR)
self.connection.cancel_on_disconnection(prompt()) self.connection.cancel_on_disconnection(prompt())
@@ -968,8 +968,8 @@ class Session:
try: try:
self.connection.cancel_on_disconnection(display_passkey()) self.connection.cancel_on_disconnection(display_passkey())
except Exception as error: except Exception:
logger.warning(f'exception while displaying passkey: {error}') logger.exception('exception while displaying passkey')
else: else:
self.input_passkey(next_steps) self.input_passkey(next_steps)
@@ -1414,8 +1414,8 @@ class Session:
if handler is not None: if handler is not None:
try: try:
handler(command) handler(command)
except Exception as error: except Exception:
logger.exception(f'{color("!!! Exception in handler:", "red")} {error}') logger.exception(color("!!! Exception in handler:", "red"))
response = SMP_Pairing_Failed_Command( response = SMP_Pairing_Failed_Command(
reason=SMP_UNSPECIFIED_REASON_ERROR reason=SMP_UNSPECIFIED_REASON_ERROR
) )
@@ -1436,8 +1436,8 @@ class Session:
# Check if the request should proceed # Check if the request should proceed
try: try:
accepted = await self.pairing_config.delegate.accept() accepted = await self.pairing_config.delegate.accept()
except Exception as error: except Exception:
logger.warning(f'exception while accepting: {error}') logger.exception('exception while accepting')
accepted = False accepted = False
if not accepted: if not accepted:
logger.debug('pairing rejected by delegate') logger.debug('pairing rejected by delegate')

View File

@@ -48,8 +48,8 @@ def _wrap_transport(transport: Transport) -> Transport:
return SnoopingTransport.create_with( return SnoopingTransport.create_with(
transport, create_snooper(snooper_spec) transport, create_snooper(snooper_spec)
) )
except Exception as exc: except Exception:
logger.warning(f'Exception while creating snooper: {exc}') logger.exception('Exception while creating snooper')
return transport return transport

View File

@@ -90,8 +90,8 @@ class PacketPump:
try: try:
# Deliver the packet to the sink # Deliver the packet to the sink
self.sink.on_packet(await self.reader.next_packet()) self.sink.on_packet(await self.reader.next_packet())
except Exception as error: except Exception:
logger.warning(f'!!! {error}') logger.exception('!!!')
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
@@ -158,10 +158,8 @@ class PacketParser:
if self.sink: if self.sink:
try: try:
self.sink.on_packet(bytes(self.packet)) self.sink.on_packet(bytes(self.packet))
except Exception as error: except Exception:
logger.exception( logger.exception(color('!!! Exception in on_packet', 'red'))
color(f'!!! Exception in on_packet: {error}', 'red')
)
self.reset() self.reset()
def set_packet_sink(self, sink: TransportSink) -> None: def set_packet_sink(self, sink: TransportSink) -> None:
@@ -378,7 +376,7 @@ class PumpedPacketSource(ParserSource):
self.terminated.set_result(None) self.terminated.set_result(None)
break break
except Exception as error: except Exception as error:
logger.warning(f'exception while waiting for packet: {error}') logger.exception('exception while waiting for packet')
if not self.terminated.done(): if not self.terminated.done():
self.terminated.set_exception(error) self.terminated.set_exception(error)
break break
@@ -409,8 +407,8 @@ class PumpedPacketSink:
except asyncio.CancelledError: except asyncio.CancelledError:
logger.debug('sink pump task done') logger.debug('sink pump task done')
break break
except Exception as error: except Exception:
logger.warning(f'exception while sending packet: {error}') logger.exception('exception while sending packet')
break break
self.pump_task = asyncio.create_task(pump_packets()) self.pump_task = asyncio.create_task(pump_packets())

View File

@@ -285,7 +285,7 @@ async def open_pyusb_transport(spec: str) -> Transport:
try: try:
device = await _power_cycle(device) # type: ignore device = await _power_cycle(device) # type: ignore
except Exception as e: except Exception as e:
logging.debug(e) logging.debug(e, stack_info=True)
logging.info(f"Unable to power cycle {hex(device.idVendor)} {hex(device.idProduct)}") # type: ignore logging.info(f"Unable to power cycle {hex(device.idVendor)} {hex(device.idProduct)}") # type: ignore
# Collect the metadata # Collect the metadata
@@ -371,9 +371,8 @@ async def _power_cycle(device: UsbDevice) -> UsbDevice:
# Device needs to be find again otherwise it will appear as disconnected # Device needs to be find again otherwise it will appear as disconnected
return usb.core.find(idVendor=device.idVendor, idProduct=device.idProduct) # type: ignore return usb.core.find(idVendor=device.idVendor, idProduct=device.idProduct) # type: ignore
except USBError as e: except USBError:
logger.error(f"Adjustment needed: Please revise the udev rule for device {hex(device.idVendor)}:{hex(device.idProduct)} for proper recognition.") # type: ignore logger.exception(f"Adjustment needed: Please revise the udev rule for device {hex(device.idVendor)}:{hex(device.idProduct)} for proper recognition.") # type: ignore
logger.error(e)
return device return device

View File

@@ -292,9 +292,9 @@ async def open_usb_transport(spec: str) -> Transport:
if self.sink: if self.sink:
try: try:
self.sink.on_packet(packet) self.sink.on_packet(packet)
except Exception as error: except Exception:
logger.exception( logger.exception(
color(f'!!! Exception in sink.on_packet: {error}', 'red') color('!!! Exception in sink.on_packet', 'red')
) )
def close(self): def close(self):

View File

@@ -317,10 +317,8 @@ class AsyncRunner:
item = await self.queue.get() item = await self.queue.get()
try: try:
await item await item
except Exception as error: except Exception:
logger.warning( logger.exception(color("!!! Exception in work queue", "red"))
f'{color("!!! Exception in work queue:", "red")} {error}'
)
# Shared default queue # Shared default queue
default_queue = WorkQueue() default_queue = WorkQueue()