1

I am trying to make sure I have set up error handling. I am not sure if I am using try, except, and return correctly.

The desired output is True or False True if the document is inserted successfully, False if not. Have I done it correctly? My concern that is that it will always return true? Not exactly sure how try/except works.Thank you.

import json
import pymongo
from bson import json_util
from pymongo import MongoClient
from pymongo import errors

connection = MongoClient('localhost', 27017)
db = connection['city']
collection = db['inspections']

def insert_document(documentToInsert):
    try:
      collection.insert_one(documentToInsert)
      return True
    except WriteConcernError as wce:
      print(wce)
      return False
    except WriteError as we:
      print(we)
      return False


def main():
    document = { 
      "id" : "11111-2019-ENFO",
      "certificate_number" : 9278806,
      "business_name" : "TAXOLOGY",
      "date" : "Feb 20 2015",
      "result" : "No Violation Issued",
      "sector" : "Accounting - 111",
      "address" :
      {
        "city" : "MISSION HILLS",
        "zip" : 91401,
        "street" : "Sepulveda",
        "number" : 1809
      }
    }

    print(insert_document(document))

main()

1 Answer 1

4

I don't see any write_concern being passed-in as an option to your writes, I would assume you might not see WriteConcernError. Check this : pymongo.write_concern.WriteConcern for examples on how to set WriteConcern . Also those error checks are only needed if you wanted to execute certain functionality if a certain type of an error occurred, As all you need is to return True / False, then you can remove all those error checks :

Code :

connection = MongoClient('localhost', 27017)
db = connection['city']
collection = db['inspections']


def insert_document(documentToInsert):
    try:
        collection.insert_one(documentToInsert)
        return True
    except Exception as e:
        print("An exception occurred ::", e)
        return False


def main():
    document = {
        "id": "11111-2019-ENFO",
        "certificate_number": 9278806,
        "business_name": "TAXOLOGY",
        "date": "Feb 20 2015",
        "result": "No Violation Issued",
        "sector": "Accounting - 111",
        "address":
        {
            "city": "MISSION HILLS",
            "zip": 91401,
            "street": "Sepulveda",
            "number": 1809
        }
    }

    print(insert_document(document))


main()
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry for stupid question but what is ::, is that some formatting or you are just printing those characters. But my other question is, if collection.insert_one has an error, does it still return True or does it skip that?
@Etra : :: It's just like we're printing it to give some space between text & actual exception when printed together, if collection.insert_one has an error it should be handled at except with function returning False .. You can test it by passing _id: 123 in your document & try inserting same document twice - as in mongo _id is unique by default it would throw an error & in expect error will be printed & then by function returns False..
That really clears it up, I was not sure how to actually get an error to test it, but I forgot about _id completely. I understand try/else now and error catching much better. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.