import pymongo
import sys
MONGO_USER = "ID"
MONGO_PASS = "Password"
def user_input():
MONGO_HOST = 'mongodb://000.000.000.000' # server address
MONGO_DB = 'databse' # database of interest in the server
connection = pymongo.MongoClient(MONGO_HOST) # connects to the remote database server
db = connection[MONGO_DB] # specifies the database we want to use
try:
log_in = db.authenticate(MONGO_USER, MONGO_PASS)
except:
log_in = False # returns False if authentication fails
finally:
return log_in,db
So, I want to raise different exceptions for different kinds of authentication errors. I want to raise an exception for in which the specified server is not open, and an exception for in which the user put wrong ID or Password. So, Something like this:
try:
log_in = db.authenticate(MONGO_USER, MONGO_PASS)
except wrong_ID_or_Password:
log_in = False
---prompt the user to try again
except something_internally_wrong_with_server:
log_in = False
print("server is wrong")
sys.exit(1)
What code should I use for each cases? I need to code that works specifically for Pymongo. I've seen Pymongo's documentation that says like
except pymongo.errors.InvalidName:
do something
but doesn't work.
Here is the documentation that I found: http://api.mongodb.com/python/current/api/pymongo/errors.html
i've already tried InvalidName: exception from that doc, but when I tried putting a wrong ID, it didn't go to that exception handler. So, when I use:
MONGO_USER = "wrong_ID"
....
except pymongo.errors.InvalidName:
print("incorrect ID")
it should go to that InvalidName: exception handler, and print "incorrect ID", but it didnt