Domanda

I want to add global exception handling object to my Flask webproject. In main module, where application class is created I've added code to override sys.excepthook. Here is simple test code:

import sys

def my_exception_hook(exception_type, value, traceback):
    print "My exception handler"
    print "  Exception type:", exception_type
    print "  Exception instance:", value
    print "  Traceback:", traceback

    sys.__excepthook__(exception_type, value, traceback)

sys.excepthook = my_exception_hook

from flask import Flask
import requests

app = Flask(__name__)

@app.route('/')
def index():
    #Exception raised here "requests.exceptions.MissingSchema" not captured by my handler
    r = requests.get('ololo', auth=('user', 'pass'))
    return "Hello, world!"

#raise Exception("AAA") #Exception raised here is successfully goes to my_exception_hook

app.run(debug=True, port=5001)

I do not want and have no possibility to envelop each call or requests module with try/catch. Also I want to handle other eaception, for example, mongoDB connection problem which may occured spontaneousely (not wheen I creating connection), please do not suggest it.

È stato utile?

Soluzione

Flask already handles exceptions in views for you. Using sys.excepthook is not the right way to handle this, the hook will never be called.

Specify a custom exception handler with Flask instead, see the Redirects and Errors section of the Quickstart manual:

from flask import render_template

@app.errorhandler(500)
def page_not_found(error):
    return 'some error message'

Flask also uses the logging module to record exceptions; configure the logging module to write anything of severity logging.ERROR to the console or a log file.

Since you use app.run(debug=True, port=5001), you'll already see exceptions printed to the console.

Note that the 500 error page is only ever invoked when debug is not set to True however; otherwise the Werkzeug debug view is invoked instead.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top