I've written an API which returns Json in the following format...
{"Success": true, Result: {...}}
{"Success": false, ExceptionId: "(some uuid)"}
The exceptions are logged. This is fine in principle for allowing someone to discuss an error without us ever telling them what it is (as a security measure). During debugging I also want to output the error message to stop me having to refer to a database all the time.
As things stand, the problem is getting useful information from the exception (either to return or log in the db)
I'm doing something like this...
try:
Ret['Result'] = <Blah>
Ret['Success'] = True
except Exception as e:
# ... Logging/ExceptionId
if Settings.DebugMode:
Ret['Exception'] = str(e)
If I put a breakpoint on the last line and inspect e
in eclipse's watch window, I get KeyError: 'Something'
, but str(e)
results in 'Something'
which is very unhelpful.
I've googled and I can't find any way to get a proper message from an exception. Apparently there used to be a .message
in v<2.4 but that's no help to me in 3.3
As an alternative, I tried doing:
Ret['Exception'] = str(type(e)) + ": " + str(e)
Which resulted in <class 'KeyError'>: 'job'
which is a little closer but it's starting to feel more and more hackish.
I also want to include a Stack Trace but have had even less luck there - I can get the __traceback__
but of course it's not serializable and calling str()
on it just results in a description of the object eg <traceback object at 0x0000000004024E48>
How can I get a decent/comprehensive error message?
By default, the stack trace is captured immediately before an exception object is thrown. Use StackTrace to get stack trace information when no exception is being thrown.
The most common method to catch and print the exception message in Python is by using except and try statement. You can also save its error message using this method. Another method is to use logger.
The stack trace contains the Exception's type and a message, and a list of all the method calls which were in progress when it was thrown.
You probably want repr
:
Ret['Exception'] = repr(e)
For the traceback, use the traceback module:
from traceback import format_exc
Ret['Traceback'] = format_exc()
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