老问题,但对于 2021 年阅读的任何人:
对于所有未明确定义的异常,可以返回 500 代码。
该函数的结构来自 Flask cookiecutter,尽管该模式对每个错误都有一个 Jinja 模板。
我没有运气自动捕获所有异常,但我发现这很DRYer,然后为每个单独的异常提供一个单独的页面。
"""
app.exceptions
==============
(python3)
"""
# app/exceptions.py
from typing import Tuple
from flask import Flask, render_template
from werkzeug.exceptions import HTTPException
EXCEPTIONS = {
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
500: "Internal Server Error",
}
# general function structure: https://github.com/cookiecutter-flask/cookiecutter-flask
def init_app(app: Flask) -> None:
"""Register error handlers."""
def render_error(error: HTTPException) -> Tuple[str, int]:
"""Render error template.
If a HTTPException, pull the ``code`` attribute; default to 500.
:param error: Exception to catch and render page for.
:return: Tuple consisting of rendered template and error code.
"""
app.logger.error(error.description)
error_code = getattr(error, "code", 500)
return (
render_template(
"exception.html",
error_code=error_code,
exception=EXCEPTIONS[error_code],
),
error_code,
)
for errcode in [400, 401, 403, 404, 405, 500]:
app.errorhandler(errcode)(render_error)
{# app/templates/exception.html #}
{% extends "base.html" %}
{# page header and browser tab #}
{% block page_name %}{{ error_code }} {{ exception }}{% endblock %}