我在代码中有一个地方,我在的键名上犯了一个错误dict
。花了一些时间来理解为什么代码没有运行,因为没有引发回溯。
下面的代码是完整的,→→→
并以问题所在的位置突出显示:
class Alert:
lock = threading.Lock()
sent_alerts = {}
@staticmethod
def start_alert_listener():
# load existing alerts to keep persistancy
try:
with open("sent_alerts.json") as f:
json.load(f)
except FileNotFoundError:
# there is no file, never mind - it will be created at some point
pass
# start the listener
log.info("starting alert listener")
client = paho.mqtt.client.Client()
client.on_connect = Alert.mqtt_connection_alert
client.on_message = Alert.alert
client.connect("mqtt.XXXX", 1883, 60)
client.loop_forever()
@staticmethod
def mqtt_connection_alert(client, userdata, flags, rc):
if rc:
log.critical(f"error connecting to MQTT: {rc}")
sys.exit()
topic = "monitor/+/state"
client.subscribe(topic)
log.info(f"subscribed alert to {topic}")
@staticmethod
def alert(client, userdata, msg):
event = json.loads(msg.payload)
log.debug(f"received alert: {event}")
→→→ if event['ok']:
# remove existing sent flag, not thread safe!
with Alert.lock:
Alert.sent_alerts.pop(msg['id'], None)
return
(...)
来自上面一行的日志是
2021-01-14 22:03:02,617 [monitor] DEBUG received alert: {'full_target_name': 'ThisAlwaysFails → a failure', 'isOK': False, 'why': 'explicit fail', 'extra': None, 'id': '6507a61c9688199a34cb006b354c8433', 'last': '2021-01-14T22:03:02.612912+01:00', 'last_ko': '2021-01-14T22:03:02.612912+01:00'}
这是dict
我要尝试错误访问的位置ok
,这应该引发异常和回溯。但是什么也没发生。该代码的作用就好像错误被静默丢弃(该方法静默失败)一样。
我试图raise Exception("wazaa")
在log.debug()
和之间放置一个if
-同样的方法,该方法此时会失败,但不会引发异常。
我不知道为什么通过追溯无法看到异常的原因?
alert()
如果这很重要,则在单独的线程中调用该方法。为了完整起见,我尝试使用follwong代码只是为了确保threading
不干扰但不干扰(我不知道这样做的原因)
import threading
class Hello:
@staticmethod
def a():
raise Exception("I am an exception")
threading.Thread(target=Hello.a).start()
输出
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:/Users/yop/AppData/Roaming/JetBrains/PyCharm2020.3/scratches/scratch_1.py", line 7, in a
raise Exception("I am an exception")
Exception: I am an exception
它似乎在中调用了您的回调try
,然后记录了该错误:
try:
self.on_message(self, self._userdata, message)
except Exception as err:
self._easy_log(
MQTT_LOG_ERR, 'Caught exception in on_message: %s', err)
if not self.suppress_exceptions:
raise
但是,我无法解释的是为什么没有例外raise
。我看不到为什么self.suppress_exceptions
对您适用,因为您从未设置过,但是请尝试:
suppress_exceptions
使用手动设置client.suppress_exceptions = False
。这不是必需的,因为这似乎是默认值,但是值得一试。
检查它显然维护的日志。不过,您需要参考文档以了解具体操作方法,因为我以前从未接触过该库。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句