In python 2.6.6, how can I capture the error message of an exception.
IE:
response_dict = {} # contains info to response under a django view. try: plan.save() response_dict.update({'plan_id': plan.id}) except IntegrityError, e: #contains my own custom exception raising with custom messages. response_dict.update({'error': e}) return HttpResponse(json.dumps(response_dict), mimetype="application/json")
This doesnt seem to work. I get:
IntegrityError('Conflicts are not allowed.',) is not JSON serializable
If you want the error class, error message, and stack trace, use sys. exc_info() . The function sys. exc_info() gives you details about the most recent exception.
If you are going to print the exception, it is better to use print(repr(e)) ; the base Exception. __str__ implementation only returns the exception message, not the type. Or, use the traceback module, which has methods for printing the current exception, formatted, or the full traceback.
Use traceback. print_exc() to print the current exception to standard error, just like it would be printed if it remained uncaught, or traceback. format_exc() to get the same output as a string.
Pass it through str()
first.
response_dict.update({'error': str(e)})
Also note that certain exception classes may have specific attributes that give the exact error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With