4

I'm writing a simple REST service with Flask. When an exception occurs in my code, I get a nice error message and an interactive debugger in my browser. However, if I call the service from the command line (e.g. with curl), or in my unit tests, and something fails, I still get the formatted (HTML) error message. I remember that I sometimes got a plain text message instead (basically just the Python error + traceback), and I don't know how Flask decides to serve plain text or HTML.

How do I make it so that Flask returns plain (non-interactive, non-HTML) error messages when accessed without a browser?

Audrius Kažukauskas
  • 13,173
  • 4
  • 53
  • 54
jdm
  • 9,470
  • 12
  • 58
  • 110

2 Answers2

7

To handle exceptions in production mode, register error handler for 500 status code. From it you can return anything you want. Here's an example that returns exception itself as plain text:

@app.errorhandler(500)
def error_500(exception):
    return str(exception), 500, {'Content-Type': 'text/plain'}

If it's API you're writing, returning JSON encoded data as application/json may be more appropriate.

Audrius Kažukauskas
  • 13,173
  • 4
  • 53
  • 54
  • Regarding the JSON output, you'll need to jsonify as normal: `return jsonify({"error": str(exception)}), 500, {'Content-Type': 'application/json'}` – robertlayton Jun 10 '18 at 23:31
5

Set app.debug = False to turn off the fancy error reporting. The documentation has more on debug mode.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284