Reputation: 15760
Folks, I am trying to check connections that error out, and log to alert if that happens.
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")
For some reason, this is not working, and is spitting out:
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
How can I catch failures and alert on them and continue my checks, instead of the script breaking out?
Thanks!
Upvotes: 3
Views: 2038
Reputation: 28292
Instead of if
/else
clause, which evaluates the statement as boolean, you can use try
and except
to catch errors:
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")
Upvotes: 2