Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to print the message inside ValidationError

I would like to know how to print the string written when raising an exception.

For example if I use

raise ValidationError("RANDOM TEXT HERE");

How can I retreive "RANDOM TEXT HERE" from within the except section.

try:
  ...
except ValidationError:
  ...
  // something like Java's ex.getMessage();
  .....

Thank you

like image 688
Rorchackh Avatar asked Apr 25 '12 00:04

Rorchackh


1 Answers

If you bind the exception to a variable, then you could get its string representation with str(exception_variable).

Namely:

try:
  ...
except ValidationError as e:
  print str(e)

Edit: Changed msg to message

Second edit: Realized that exceptions are inconsistent between storing messages in msg vs message. str(exception) seems to be the most consistent.

like image 75
Zach Avatar answered Nov 14 '22 22:11

Zach