D
D
Danil Gorev2021-09-08 09:34:27
Python
Danil Gorev, 2021-09-08 09:34:27

How to output full traceback from Exception object?

I wrote a custom Middleware for Django to catch errors and store them (no matter where, be it ELK or Sentry). Inside the class, I implemented the process_exception function, which receives: request - an HTTP request in Django format, exception - the error itself, the successor of Exception.

When I try to output an exception somewhere in string format, I get only the error message itself, without specifying the module in which it originated. If I execute the response_for_exception(request, exception) jang, then along with the trace, I get a bunch of heaped up HTML code that makes it difficult to find the trace.

Now the code looks something like this:

def process_exception(self, request, exception: Exception):
    error_msg = response_for_exception(request, exception).content.decode('utf-8')
    log({ 'error_msg': error_msg })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stefan, 2021-09-08
@ketovv

def process_exception(self, request, exception: Exception):
    import traceback
    error_msg = response_for_exception(request, exception).content.decode('utf-8')
    log({ 'error_msg': error_msg, "traceback": traceback.format_exc() })

In theory, this should work, but I’m not sure, try again when you catch it in try / except, push this construction, and forward it to the traceback function
try:
    # Тут типо где ждем ошибку:
except Lalal:
    import traceback
    trace = traceback.format_exc()
    error_handler.process_exception(request, exception: Exception, trace):

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question