I'm pulling my hair out trying to get pymongo to error out when code can't connect to a MongoD instance. It seems like no matter what I do the 'pymongo.errors.ConnectionFailure' is not working. I've tried this on localhost and a remote mongoD instance. When I use the mongoclient shell ('mongo –host xx.xx.xx.xx') from the same system, I get the proper 'connection refused'. Other exceptions are working, but not 'ConnectionFailure.' Note that when I run tshark sniffer on mongod instance host, I see the proper TCP RST on closed port for connection refused. Mongod is not listening, but the pymongo ConnectionFailure can't catch a failed connection.
python version: 2.7.10
pymongo version: 3.2
What could I be missing, or steps to troubleshoot? In this example below, mongod is not running on localhost. I also stop it on remote host. In both instances, the exception error is not caught, and pymongo code appears to think it is connected.
Code:
import pymongo
try:
pymongo.MongoClient('localhost:27017')
except pymongo.errors.ConnectionFailure, e:
print "Could not connect: %s" % e
Best Answer
As MongoClient Doesn't return a valuable response that can help in connectin state this will work just fine.