如何为 404 返回自定义页面并记录到 Prometheus?

解读

国内生产环境对“可观测性”与“用户体验”并重:

  1. 404 不能直接把 Starlette 默认 JSON 抛给前端,需返回带公司品牌、统一错误码、SEO 友好的 HTML 或标准化 JSON。
  2. 同时要把 404 次数打到 Prometheus,方便 SRE 做“错误率 TOP10 接口”告警。
  3. 面试时,考官会追问“你打的是哪个指标?label 怎么设计?会不会造成 cardinality 爆炸?”、“如果放在中间件里,会不会把 404 和 405 混到一起?”、“如何单元测试?”——必须给出可落地的代码与权衡。

知识点

  1. FastAPI 异常处理链:Starlette 的 HTTPException → FastAPI 的 exception_handler → 可叠加中间件。
  2. Prometheus 客户端:Counter 与 Histogram 区别;label 维度控制(status、method、endpoint 模板路径)。
  3. 路径匹配顺序:精确路由 → 前缀路由 → 404;因此 404 只能在“兜底的 exception_handler”里捕获。
  4. 自定义响应:返回 HTML 用 Response(content=..., media_type="text/html");返回 JSON 用 JSONResponse 或自定义模型。
  5. 指标暴露:使用 prometheus-client 的 make_asgi_app() 挂载 /metrics;多进程场景需用 CollectorRegistry 或官方推荐的 prometheus_fastapi_instrumentator。
  6. 单元测试:TestClient 触发不存在的路由,检查 resp.status_code、resp.text 包含品牌信息;访问 /metrics 验证 404_total 递增。

答案

# main.py
from fastapi import FastAPI, Request, Response
from fastapi.responses import HTMLResponse
from prometheus_client import Counter, make_asgi_app
import uvicorn

# 1. 定义指标:只带可控 label,避免把完整路径打进去造成爆炸
not_found_counter = Counter(
    "http_404_total",
    "Total number of 404 responses",
    labelnames=["method", "endpoint_rule"]   # endpoint_rule 用模板路径或固定字符串
)

# 2. 自定义 404 页面
html_404 = """
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>页面不存在</title></head>
<body>
    <div style="text-align:center;padding:80px;">
        <h1>404 - 您访问的页面不存在</h1>
        <p><a href="/">返回首页</a></p>
    </div>
</body>
</html>
"""

# 3. 工厂函数创建应用,方便测试
def create_app() -> FastAPI:
    app = FastAPI(docs_url=None, redoc_url=None)  # 关闭文档,防止扫描

    # 4. 注册 404 异常处理器
    @app.exception_handler(404)
    async def custom_404_handler(request: Request, _exc):
        # 记录指标:method 是大写 GET/POST,endpoint_rule 用固定值"404"
        not_found_counter.labels(method=request.method, endpoint_rule="404").inc()
        return HTMLResponse(content=html_404, status_code=404)

    # 5. 示例正常接口
    @app.get("/api/status")
    def status():
        return {"status": "ok"}

    # 6. 挂载 /metrics
    metrics_app = make_asgi_app()
    app.mount("/metrics", metrics_app)

    return app

if __name__ == "__main__":
    uvicorn.run("main:create_app", factory=True, host="0.0.0.0", port=8000)

验证步骤(本地)

  1. curl http://localhost:8000/api/status → 200
  2. curl http://localhost:8000/nopage → 返回自定义 HTML,状态码 404
  3. curl http://localhost:8000/metrics → 出现
    http_404_total{method="GET",endpoint_rule="404"} 1.0
    
    每访问一次不存在的路径,该值递增。

拓展思考

  1. 标签细化还是收敛?
    如果把实际访问路径 {path} 当 label,攻击者可以刷随机路径导致 Prometheus 内存暴涨;国内大厂普遍只打“方法+固定字符串”或“方法+路由模板”,再靠日志链路追踪明细。
  2. 405 与 404 分离
    405 是“路径存在但方法不对”,Starlette 会单独抛出 405,可再写一个 exception_handler(405) 并打点 http_405_total,方便区分“接口写错”和“前端乱调”。
  3. 多进程部署
    gunicorn -k uvicorn.workers.UvicornWorker -w 4 时,需用 prometheus_client.multiprocess.MarkProcessCollector 或切换到 prometheus_fastapi_instrumentator,否则指标只统计 worker0。
  4. 接入 Grafana 告警
    配置 rate(http_404_total[5m]) > 0.05 即 5 分钟内 404 率超过 5% 就发飞书/钉钉,同时关联 Loki 日志定位 Top404 路径。
  5. 前端 SPA 回退
    若前后端分离且前端路由用 history 模式,可把 404 处理器改成“当 Accept: text/html 时返回 index.html,其他 Accept 返回 JSON”,兼顾 SEO 与接口规范。