Flask中如何自定义错误页面?

解读

国内一线/二线互联网公司面试时,这道题通常不是“写个404.html”那么简单,而是考察候选人是否理解:

  1. Flask 错误处理注册机制(errorhandler、app_errorhandler、Blueprint 级)
  2. 与生产部署(Nginx + uWSGI/Gunicorn)结合时,错误页面如何保持一致性
  3. 日志、监控、APM(如阿里云 SLS、腾讯云 CLS、Prometheus)如何联动
  4. RESTful 与 SSR 双协议并存时,错误响应如何区分 JSON 与 HTML
  5. 蓝本拆分、循环引用、工厂模式下的延迟注册顺序
  6. 安全:防止错误回显泄露堆栈、统一返回头、CSP 策略
  7. 单元测试:如何断言状态码与自定义页面

面试官希望听到“能跑、能测、能上线”的完整闭环,而不是 Demo 级代码。

知识点

  1. 错误类型:HTTPException(404、405…)、业务自定义(BusinessError)、Python 原生异常(ValueError)。
  2. 注册方式:
    • @app.errorhandler(code_or_exception)
    • @blueprint.app_errorhandler(code_or_exception)
    • app.register_error_handler(code_or_exception, func)
  3. 返回值协议:可返回 (response, status, headers) 三元组,或 Response 对象,或字符串(自动包装为 200,需手动 status)。
  4. 模板渲染:render_template 与主题继承,静态文件 CDN 加速。
  5. 内容协商:request.accept_mimetypes.best_match([‘application/json’, ‘text/html’])。
  6. 日志:current_app.logger.error(exc_info=True) 写入 gunicorn.error,对接 Sentry/CLS。
  7. 安全:生产环境关闭 DEBUG,统一错误 ID 返回,堆栈只在服务端留存。
  8. 测试:test_client 触发路由,断言 data 包含自定义关键字,status_code 精确匹配。

答案

以下示例覆盖“工厂模式 + 蓝本 + REST/SSR 双协议 + 日志 + 测试”,可直接写进简历项目。

# app/__init__.py
from flask import Flask, render_template, request, jsonify, current_app
from werkzeug.exceptions import HTTPException
import uuid

def create_app(config_name='prod'):
    app = Flask(__name__, static_folder='static', template_folder='templates')
    app.config.from_mapping(
        SECRET_KEY='replace-me',
        JSON_AS_ASCII=False
    )

    # 统一错误处理
    def error_handler(error):
        # 生成追踪 ID,方便排障
        trace_id = str(uuid.uuid4())
        # 日志落盘
        current_app.logger.error(
            f"[{trace_id}] {request.remote_addr} {request.method} {request.url} -> {error.code}",
            exc_info=True
        )
        # 内容协商
        if request.accept_mimetypes.best_match(['application/json', 'text/html']) == 'application/json':
            return jsonify(code=error.code, message=error.description, trace_id=trace_id), error.code
        # SSR 返回
        return render_template(f'errors/{error.code}.html', trace_id=trace_id), error.code

    # 批量注册常见 HTTP 错误
    for code in [400, 401, 403, 404, 405, 500]:
        app.register_error_handler(code, error_handler)

    # 处理非 HTTPException 的裸异常
    def fallback_handler(e):
        trace_id = str(uuid.uuid4())
        current_app.logger.error(f"[{trace_id}] unhandled: {e}", exc_info=True)
        if request.accept_mimetypes.best_match(['application/json', 'text/html']) == 'application/json':
            return jsonify(code=500, message='Internal Server Error', trace_id=trace_id), 500
        return render_template('errors/500.html', trace_id=trace_id), 500

    app.register_error_handler(Exception, fallback_handler)

    # 注册蓝本
    from app.views import bp
    app.register_blueprint(bp)

    return app

模板目录结构

templates/
└── errors/
    ├── 404.html
    ├── 500.html

404.html 示例

{% extends "base.html" %}
{% block title %}404{% endblock %}
{% block body %}
<h1>页面飞走了</h1>
<p>追踪 ID:{{ trace_id }}</p>
{% endblock %}

单元测试

# tests/test_error.py
import pytest
from app import create_app

@pytest.fixture
def client():
    app = create_app('test')
    return app.test_client()

def test_404_html(client):
    rv = client.get('/not-exist', headers={'Accept': 'text/html'})
    assert rv.status_code == 404
    assert b'页面飞走了' in rv.data

def test_404_json(client):
    rv = client.get('/not-exist', headers={'Accept': 'application/json'})
    assert rv.status_code == 404
    assert rv.json['code'] == 404
    assert 'trace_id' in rv.json

生产部署要点

  • Gunicorn 启动加 --capture-output --error-logfile -,确保错误日志进 stdout,方便容器收集。
  • Nginx 统一 error_page 404 /404.html; 但保持 proxy_intercept_errors on;,让 Flask 接管,避免双重维护。
  • 阿里云 SLS 配置正则提取 trace_id,实现秒级定位。

拓展思考

  1. 微服务链路透传:利用 X-B3-TraceId 或 W3C traceparent 头部,把错误 ID 与链路追踪系统(Jaeger、SkyWalking)打通,实现跨服务排障。
  2. 限流与熔断:当 5xx 比例突增,可结合 Flask-Limiter 与阿里 MSE Sentinel,动态降级并返回友好页面,而非持续打爆日志。
  3. 灰度发布:利用 Nginx+Consul 做按版本分流,新旧两套错误页并存,通过监控 trace_id 分布验证灰度效果。
  4. 前端 SPA:若采用 React/Vue,可约定后端只返回 JSON,错误页由前端路由接管;此时后端需额外返回 code: 499 之类自定义状态,供前端弹窗或跳转。
  5. 自动化回归:在 CI 阶段用 pytest-xdist 并发扫描全站路由,自动收集所有 4xx/5xx 模板,防止上线时模板缺失导致 500。