Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the full exception type/message and stack trace

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?

like image 951
Basic Avatar asked Apr 16 '13 11:04

Basic


People also ask

How do I get full stack trace of exception?

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.

How do I get full exception messages in Python?

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.

Does exception message contain stack trace?

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.


1 Answers

You probably want repr:

Ret['Exception'] = repr(e)

For the traceback, use the traceback module:

from traceback import format_exc
Ret['Traceback'] = format_exc()
like image 71
ecatmur Avatar answered Oct 14 '22 22:10

ecatmur