0

FAILED SQL: INSERT INTO \"brand\" (\"brand_id\", \"name\", \"notification_email\", \"notification_phone\", \"created_at\", \"updated_at\") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s)\nPymongo error: {\'index\': 0, \'code\': 11000, \'errmsg\': \'E11000 duplicate key error collection: f2fretaildev.brand index: name_1 dup key: { : \"shyamalas\" }\'}\nVersion: 1.2.26"

This is the error on duplicate key while adding data with djongo (django mongodb orm)

Is there a way get the pymongo error inside it as a json? I tried json.dumps and json.loads which did not work

yash
  • 1,357
  • 2
  • 23
  • 34

1 Answers1

1

The trouble is that the error messages isn't properly formed JSON. I had to do some conditioning; The below code is just to give you an approach. It is pretty fragile in that if the error message changes, it may fail - you will have to deal with edge cases.

import json


error_msg = """
    FAILED SQL: INSERT INTO \"brand\" (\"brand_id\", \"name\", \"notification_email\", \"notification_phone\", \"created_at\",
     \"updated_at\") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s)\nPymongo error: {\'index\': 0, \'code\': 11000, 
     \'errmsg\': \'E11000 duplicate key error collection: f2fretaildev.brand index: name_1 dup key: 
     { : \"shyamalas\" }\'}\nVersion: 1.2.26"
"""

key = "Unknown"
try:
    mongo_msg = error_msg.split('Pymongo error:')[1].split('Version:')[0].replace('\n','').replace('"','##')\
        .replace("'", '"').replace("{ :", " ").replace("## }", "##").replace('##', '')
    as_dict = json.loads(mongo_msg)
    error_msg = as_dict['errmsg']
    value = error_msg.split('key:')[1].strip()
    print(error_msg)
    print(value)
except:
    # Log it, print it, try something different
    pass
SteveJ
  • 3,034
  • 2
  • 27
  • 47