Python 在 Flask 中捕获 500 服务器错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14993318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Catching a 500 server error in Flask
提问by J-bob
I love Flask's error catching. It's beautifully simple:
我喜欢 Flask 的错误捕捉。它非常简单:
@app.errorhandler(404)
def pageNotFound(error):
return "page not found"
works like charm. But it doesn't work for the 500 error code. I want to catch Python errors when something goes wrong an exception is raised in the code. Is that possible?
像魅力一样工作。但它不适用于 500 错误代码。我想在出现问题时捕获 Python 错误并在代码中引发异常。那可能吗?
I should note that if I explicitly call return abort(500)in a view then the 500 errorhandler does work. So this is explicitly for when the Python code fails.
我应该注意,如果我显式调用return abort(500)视图,那么 500 错误处理程序确实有效。所以这是明确的,当 Python 代码失败时。
Is this possible?
这可能吗?
采纳答案by Mark Hildreth
What you have described is, by default, how Flask works. My assumption is that you are running in debug mode, and therefore exceptions are being shown to you in the debug screen. Make sure debug mode is off, then try again. Here is a comment directly from the code itself:
你所描述的是,默认情况下,Flask 是如何工作的。我的假设是您正在调试模式下运行,因此在调试屏幕中会向您显示异常。确保调试模式关闭,然后重试。这是直接来自代码本身的注释:
Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used. If no such handler exists, a default 500 internal server error message is displayed.
发生未捕获的异常时启动的默认异常处理。在调试模式下,异常将立即重新引发,否则将被记录并使用 500 内部服务器错误的处理程序。如果不存在此类处理程序,则会显示默认的 500 内部服务器错误消息。
回答by Joe
It works fine in my side:
它在我身边工作正常:
from flask import Flask ,url_for,render_template,request,abort
from werkzeug.debug import get_current_traceback
app = Flask(__name__)
@app.route('/')
def index():
try:
raise Exception("Can't connect to database")
except Exception,e:
track= get_current_traceback(skip=1, show_hidden_frames=True,
ignore_system_exceptions=False)
track.log()
abort(500)
return "index"
@app.errorhandler(500)
def internal_error(error):
return "500 error"
@app.errorhandler(404)
def not_found(error):
return "404 error",404
if __name__== "__main__":
app.run(debug=True)
Flask will not set the error code for you, so make sure to also provide the HTTP status code when returning a response.
Flask 不会为您设置错误代码,因此请确保在返回响应时也提供 HTTP 状态代码。
回答by WebQube
here is my code snippt
这是我的代码片段
@app.route('/')
def index():
raise Exception("Can't connect to database")
@app.errorhandler(Exception)
def exception_handler(error):
return "!!!!" + repr(error)
回答by elachell
My solution to this was to turn on the propagation of exceptions, by modifying the config dictionary:
我对此的解决方案是通过修改配置字典来开启异常传播:
app = Flask(__name__)
...
app.config['PROPAGATE_EXCEPTIONS'] = True
Look at this other related question: Flask app raises a 500 error with no exception
回答by hmir
this code catching 500 status code and get exception error
此代码捕获 500 状态代码并获取异常错误
@app.errorhandler(Exception)
def all_exception_handler(e):
error = str(traceback.format_exc())
回答by Makan
The issue is that within the code, not all Exceptions are HTTPException, but Flask catches these by default and returns a generic 500 error response (which may or may not include the original error message as described by @Mark Hildreth). Thus, using @app.errorhandler(500)will not catch those errors, since this happens before Flask returns the generic 500 error.
问题是在代码中,并非所有 Exceptions 都是HTTPException,但 Flask 会默认捕获这些并返回通用 500 错误响应(其中可能包含也可能不包含@Mark Hildreth 描述的原始错误消息)。因此, using@app.errorhandler(500)不会捕获这些错误,因为这发生在 Flask 返回通用 500 错误之前。
You would need to have a generic errorhandler(Exception)which works similar to except Exception:in python, which captures everything. A good solution is provided in Flask pallets projects:
你需要一个通用的errorhandler(Exception),它的工作原理类似于except Exception:python,它可以捕获所有内容。在Flask 托盘项目中提供了一个很好的解决方案:
from werkzeug.exceptions import HTTPException
@app.errorhandler(Exception)
def handle_exception(e):
# pass through HTTP errors. You wouldn't want to handle these generically.
if isinstance(e, HTTPException):
return e
# now you're handling non-HTTP exceptions only
return render_template("500_generic.html", e=e), 500
You can also return JSON if you'd like and also include the original error message if you're in debug mode. E.g.
如果您愿意,也可以返回 JSON,如果您处于调试模式,还可以包含原始错误消息。例如
from flask import jsonify
from werkzeug.exceptions import HTTPException
debug = True # global variable setting the debug config
@app.errorhandler(Exception)
def handle_exception(e):
if isinstance(e, HTTPException):
return e
res = {'code': 500,
'errorType': 'Internal Server Error',
'errorMessage': "Something went really wrong!"}
if debug:
res['errorMessage'] = e.message if hasattr(e, 'message') else f'{e}'
return jsonify(res), 500

