Your current code works fine, but generally you don't want to catch Exception
because this will mask other errors in your code. For example, if I take your code snippet and put it in a file and then run it...I get no error messages, even though I have not imported the vobject
module. This is because that code is actually raising a NameError
:
Traceback (most recent call last):
File "foo.py", line 2, in <module>
vobj = vobject.readOne(vcard_readable)
NameError: name 'vobject' is not defined
but because you're catching all exceptions, you're hiding it. A better technique is to catch only the specific exceptions you expect to receive from the vobject
module, and let others percolate up normally.
For vobject
, all of the exceptions it raises are going to be subclasses of vobject.base.VObjectError
, so the following code would suffice:
try:
vobj = vobject.readOne(vcard_readable)
except vobject.base.VObjectError as e:
error_message = {
"valid": False,
"reason": "Invalid vCard\n{0}".format(e)}