Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Getting the error message of an exception

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 
like image 836
Hellnar Avatar asked Dec 16 '10 12:12

Hellnar


People also ask

How do I get exception error in Python?

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.

How do I print error try except in Python?

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.

How do you access exception data in Python?

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.


1 Answers

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.

like image 68
Ignacio Vazquez-Abrams Avatar answered Sep 19 '22 06:09

Ignacio Vazquez-Abrams