3

伙计们,我正在尝试检查错误的连接,并记录以提醒是否发生这种情况。

credentials = pika.PlainCredentials(username, password)
parameters = pika.ConnectionParameters(
    credentials=credentials,
    host='localhost',
    port=tcpport,
    virtual_host='/vhost')
if pika.BlockingConnection(parameters):
    log_error("RabbitMQ Accepts non-SSL Connections")
else:
    log_info("RabbitMQ Not accepting non-SSL connections")

出于某种原因,这不起作用,并且正在吐出:

WARNING:pika.adapters.base_connection:Connection to 127.0.0.1:8080 failed: [Errno 111] Connection refused
Traceback (most recent call last):
  File "./rabbit_test.py", line 141, in <module>
    main()
  File "./rabbit_test.py", line 129, in main
    check_non_ssl('username', 'password')
  File "./rabbit_test.py", line 40, in check_non_ssl
    if pika.BlockingConnection(parameters):
  File "/usr/lib/python2.6/site-packages/pika/adapters/blocking_connection.py", line 107, in __init__
    super(BlockingConnection, self).__init__(parameters, None, False)
  File "/usr/lib/python2.6/site-packages/pika/adapters/base_connection.py", line 62, in __init__
    on_close_callback)
  File "/usr/lib/python2.6/site-packages/pika/connection.py", line 590, in __init__
    self.connect()
  File "/usr/lib/python2.6/site-packages/pika/adapters/blocking_connection.py", line 206, in connect
    if not self._adapter_connect():
  File "/usr/lib/python2.6/site-packages/pika/adapters/blocking_connection.py", line 275, in _adapter_connect
    raise exceptions.AMQPConnectionError(1)
pika.exceptions.AMQPConnectionError: 1

我怎样才能捕捉到失败并提醒他们并继续我的检查,而不是脚本爆发?

谢谢!

4

1 回答 1

2

代替将语句评估为布尔值的if/else子句,您可以使用tryandexcept来捕获错误:

try:
    pika.BlockingConnection(parameters)
    log_error("RabbitMQ Accepts non-SSL Connections")
except: # if the anything goes wrong, go here
    log_info("RabbitMQ Not accepting non-SSL connections")
于 2013-11-13T21:14:18.533 回答