6

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
  • 704
  • 2
  • 12
  • 33
  • 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

9

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
  • 300,191
  • 65
  • 633
  • 696
  • 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
  • 16,802
  • 32
  • 96
  • 149
  • Missing parentheses – A X Jan 01 '21 at 02:08
  • For your example to work as intended you should use format_exception(). The print_exception() prints the exception and returns None. The print() function call does not actually print anything. – David42 Jan 30 '23 at 01:42