Skip to content

Error Handling

统一处理异常与错误页面,提高可维护性与用户体验。

错误处理器:

python
from flask import render_template

@app.errorhandler(404)
def not_found(e):
    return render_template("404.html"), 404

@app.errorhandler(500)
def server_error(e):
    return render_template("500.html"), 500

自定义异常:

python
class APIError(Exception):
    code = 400
    message = "Bad Request"

@app.errorhandler(APIError)
def handle_api_error(e):
    return {"error": e.message}, e.code

蓝图级处理:在蓝图对象上使用 register_error_handler

日志结合:严重错误记录日志,参见 Logging 章节。