简体   繁体   中英

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

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.

I know this is old question, but I also faced same issue and I write my solution for anyone needs in future.

When I use e variable, it gave me a list , so I used e.message

 try: ... except ValidationError as e: print e.message

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM