4

I have some code written in python flask, where I have a function as follows:

@app.errorhandler(500)
def internal_error(exception):
    print "500 error caught"

But this message is not sufficient enough to provide me with enough information. I just want to print the traceback for the exception that is passed to errorhandler. Is there any way to do this simple thing?

Sanjiban Bairagya
  • 634
  • 2
  • 10
  • 30
  • If you are running flask behind a proxy like gunicorn or uwsgi, you will not be able to use the flask debugger. A much better solution is to run the flask standalone server with `debug=True` enabled to see the full debugger. You would then access it (by default) at http://www.example.com:5000 – Dan Safee Dec 09 '15 at 11:40

2 Answers2

8

Assuming that the error handler is called from within a context when the exception and traceback are still available from sys, you should be able to use traceback.format_exc.

import traceback

@app.errorhandler(500)
def internal_error(exception):
    print "500 error caught"
    print traceback.format_exc()
mgilson
  • 283,004
  • 58
  • 591
  • 667
  • So, I won't need to use the passed argument `exception` in printing the traceback? Just `traceback.format_exc()` will suffice? – Sanjiban Bairagya Dec 09 '15 at 06:58
  • It _should_. I don't know the details of Flask's exception handling, but usually, the exception (and traceback, etc) are available from [`sys.exc_info()`](https://docs.python.org/2/library/sys.html#sys.exc_info), so `traceback` doesn't need a reference to the exception or the traceback. – mgilson Dec 09 '15 at 07:02
1

I think you can solve it like this:

import sys
import traceback

@app.errorhandler(500)
def internal_error(exception):
    print("500 error caught")
    etype, value, tb = sys.exc_info()
    print(traceback.print_exception(etype, value, tb))

You can print the traceback information

GoingMyWay
  • 15,546
  • 27
  • 90
  • 132