Python 3 引入了异常链,因此:
import logging
logger = logging.getLogger(__name__)
class MyException(Exception):
pass
def blow_up():
try:
impossible = 42 / 0
except ZeroDivisionError as zde:
raise MyException('Uh oh!') from zde
try:
blow_up()
except:
logger.exception('It blew up!')
产生这个:
It blew up!
Traceback (most recent call last):
File "ka-boom.py", line 10, in blow_up
impossible = 42 / 0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "ka-boom.py", line 15, in <module>
blow_up()
File "ka-boom.py", line 12, in blow_up
raise MyException('Uh oh!') from zde
MyException: Uh oh!
但是当在 Flask View 方法中抛出未处理的异常时,__cause__
不会被记录,这使得调试变得困难。
我能做到:
@app.errorhandler(Exception)
def better_exception_handler(error):
current_app.logger.exception('Whoopsie!')
return 'Internal server error', 500
但是我觉得像这样捕捉所有的异常不太舒服,感觉不太优雅。有没有办法让 Flask 的内置异常处理程序记录链接的异常?
最佳答案
你能提供你正在使用的 Python 和 Flask 的版本吗?使用 Python 3.5.2 和 Flask 0.12.1 我明白你所说的应该发生什么。
from flask import Flask
app = Flask(__name__)
@app.route('/error')
def error_out():
try:
blow_up()
except:
app.logger.exception('it blew up!')
return 'something went wrong'
return 'everything is a-ok!'
def blow_up():
try:
impossible = 42 / 0
except ZeroDivisionError as zde:
raise MyExc('Uh oh!') from zde
class MyExc(Exception):
pass
if __name__ == "__main__":
app.run()
为我点击 localhost:5000/error
将在控制台中记录以下内容:
Seaking:flask-err rdbaker $ ~/.pyenv/versions/3.5.2/bin/python app.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2017-05-15 12:19:52,229] ERROR in app: it blew up!
Traceback (most recent call last):
File "app.py", line 21, in blow_up
impossible = 42 / 0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "app.py", line 12, in error_out
blow_up()
File "app.py", line 23, in blow_up
raise MyExc('Uh oh!') from zde
MyExc: Uh oh!
127.0.0.1 - - [15/May/2017 12:19:52] "GET /error HTTP/1.1" 200 -
我在浏览器中看到文本 something went wrong
。
关于python-3.x - 如何让 Flask 记录未处理异常中的链式异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43881266/