如何在 Tornado 中实现符合 RFC 7807 的标准化错误响应格式?

解读

国内面试官问这道题,并不是想听你背 RFC 7807 字段,而是考察三点:

  1. 是否知道 Tornado 的异常处理链路(raise → write_error → finish)
  2. 能否把“业务错误”与“HTTP 错误”分离,并统一序列化成国内常用的 JSON 格式
  3. 是否具备工程化思维:错误码可配置、可国际化、可审计,且不改一行业务代码就能让旧接口直接升级

一句话:用最小侵入方式,让线上所有 4xx/5xx 都自动吐出国内前端同学最爱解析的 {type, title, status, detail, instance},同时保留 Tornado 的高并发优势。

知识点

  1. RFC 7807 字段语义与 MIME 类型 application/problem+json
  2. Tornado 异常流:HTTPError → RequestHandler.write_error(status_code, **kwargs) → finish()
  3. 自定义基类 + Mixin:重写 write_error,利用 self.set_header 与 self.finish
  4. 业务异常码映射:维护 error_catalog.yaml,支持 I18n(self.locale.translate)
  5. 日志与追踪:在 write_error 里写一条带 request_id 的 JSON 日志,方便 ELK 链路追踪
  6. 性能注意:write_error 运行在 IOLoop 同一线程,禁止同步 IO;如需外部告警,扔消息队列
  7. 国内合规:返回体里不带敏感栈信息,但可放加密后的 trace_id 供运维反查

答案

  1. 定义 RFC 7807 错误模型(problem.py)
from typing import Optional, Dict, Any
import json

class Problem:
    def __init__(self,
                 status: int,
                 title: str,
                 type_: str = "about:blank",
                 detail: Optional[str] = None,
                 instance: Optional[str] = None,
                 extra: Optional[Dict[str, Any]] = None):
        self.status = status
        self.title = title
        self.type = type_
        self.detail = detail or ""
        self.instance = instance or ""
        self.extra = extra or {}

    def as_dict(self) -> Dict[str, Any]:
        d = {
            "status": self.status,
            "title": self.title,
            "type": self.type,
            "detail": self.detail,
            "instance": self.instance,
        }
        d.update(self.extra)
        return d
  1. 定义业务异常基类(exceptions.py)
class BizError(Exception):
    def __init__(self, code: str, detail: str = "", status: int = 400):
        self.code = code          # 业务错误码,如 A0101
        self.detail = detail
        self.status = status
        super().__init__(self.detail)
  1. 自定义 Handler 基类(base.py)
from tornado.web import RequestHandler
from problem import Problem
from exceptions import BizError
import uuid

class BaseHandler(RequestHandler):
    def prepare(self):
        # 每个请求生成 request_id,方便链路追踪
        self.request_id = self.request.headers.get("X-Request-Id") or str(uuid.uuid4())

    def write_error(self, status_code: int, **kwargs):
        # 1. 默认用 RFC 7807 字段
        exc = kwargs.get("exc_info")[1] if kwargs.get("exc_info") else None
        if isinstance(exc, BizError):
            # 业务异常
            problem = Problem(
                status=exc.status,
                title=self.locale.translate(exc.code),
                detail=exc.detail,
                instance=self.request.path,
                extra={"code": exc.code, "request_id": self.request_id}
            )
        elif isinstance(exc, HTTPError):
            # Tornado 原生 HTTPError
            problem = Problem(
                status=exc.status_code,
                title=exc.reason or "Unknown Error",
                detail=str(exc),
                instance=self.request.path,
                extra={"request_id": self.request_id}
            )
        else:
            # 兜底
            problem = Problem(
                status=status_code,
                title="Internal Server Error",
                detail="服务器开小差,请稍后重试",
                instance=self.request.path,
                extra={"request_id": self.request_id}
            )

        # 2. 设置响应头
        self.set_header("Content-Type", "application/problem+json; charset=utf-8")
        # 3. 返回 JSON
        self.finish(json.dumps(problem.as_dict(), ensure_ascii=False))

    def log_exception(self, typ, value, tb):
        # 统一写日志,供 ELK 收集
        self.application.logger.error(
            "exception",
            exc_info=(typ, value, tb),
            extra={
                "request_id": getattr(self, "request_id", None),
                "uri": self.request.uri,
                "remote_ip": self.request.remote_ip,
            }
        )
  1. 启动文件(main.py)
from tornado.web import Application, HTTPError
from tornado.ioloop import IOLoop
from base import BaseHandler
from exceptions import BizError
import logging

class DemoHandler(BaseHandler):
    def get(self):
        raise BizError("A0101", "手机号格式错误", 400)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    app = Application([
        (r"/demo", DemoHandler),
    ], logger=logging.getLogger("tornado.application"))
    app.listen(8888)
    IOLoop.current().start()
  1. 验证
curl -H "X-Request-Id: 123" http://127.0.0.1:8888/demo

返回:

{
  "status": 400,
  "title": "手机号格式错误",
  "type": "about:blank",
  "detail": "手机号格式错误",
  "instance": "/demo",
  "code": "A0101",
  "request_id": "123"
}

状态码 400,Content-Type 为 application/problem+json,完全符合 RFC 7807,且前端可直接按字段解析。

拓展思考

  1. 多语言:把 error_catalog.yaml 按语言区分,如 zh_CN/A0101: "手机号格式错误"、en_US/A0101: "Invalid phone format",在 write_error 里用 self.locale.translate 动态加载
  2. 错误码分层:1 开头参数错误、2 开头业务规则、3 开头第三方依赖、9 开头系统级,方便监控告警分级
  3. 灰度追踪:在响应头里再加 X-Trace-Id,运维通过 jaeger 或 skywalking 直接跳转链路
  4. 性能压测:Tornado 单线程模型下,write_error 里禁止任何同步 IO;如需把错误事件推送到 Kafka,使用 tornado.ioloop.IOLoop.current().add_callback 异步投递
  5. 兼容老项目:旧接口原来直接 self.write({"errcode": x, "errmsg": y}),可在 write_error 里判断 self.get_query_argument("v", None) == "1",老版本走兼容字段,新版本走 RFC 7807,实现平滑升级