0
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

Eric Kim
  • 2,493
  • 6
  • 33
  • 69
  • Also, you can handle multiple exceptions with the same code inside (like the above) in a single line. Refer to https://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block – yash Oct 30 '17 at 23:41
  • I saw that documentation, but that's not what I want. I know how to handle multiple exceptions. The thing that I want to know is specific to Pymongo, and the code that works for Pymongo. – Eric Kim Oct 30 '17 at 23:47
  • Can you put that attempt in your question? – roganjosh Oct 30 '17 at 23:55

0 Answers0