Flask和sys.excepthook [英] Flask and sys.excepthook

查看:33
本文介绍了Flask和sys.excepthook的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将全局异常处理对象添加到我的Flask Web项目中.在创建应用程序类的主模块中,我添加了代码以覆盖 sys.excepthook .这是简单的测试代码:

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)

我不希望也不可能用 try/catch 包围每个呼叫或 requests 模块.另外,我还想处理其他方法,例如mongoDB连接问题,它可能是自发发生的(不是我创建连接时出现的),请不要提出它.

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.

推荐答案

Flask已经为您处理了视图中的异常.使用 sys.excepthook 不是正确的处理方式,因此永远不会调用该钩子.

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.

用Flask指定一个自定义异常处理程序,请参见重定向和快速入门手册的错误部分:

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还使用 logging 模块记录异常;配置日志记录模块以将严重性为 logging.ERROR 的任何内容写入控制台或日志文件.

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.

由于您使用的是 app.run(debug = True,port = 5001),因此您已经可以看到打印到控制台的异常.

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

请注意,只有在debug未设置为 True 时,才调用500错误页面.否则,将调用 Werkzeug调试视图.

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.

这篇关于Flask和sys.excepthook的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆