bigywater.tech
Flask · 11

abort() 如何生成错误响应

abort(404) 是怎么变成一个 HTTP 响应的?错误页长什么样?能带自己的头、正文吗?不认识的状态码会怎样?这篇逐个试。

31
werkzeug 内置的 HTTP 异常状态码数
207
abort(404) 默认错误页的 Content-Length(字节)
LookupError
对未注册的状态码 abort 时抛出的异常类型

abort(404) 的响应

实测 · 本机执行输出
   404 NOT FOUND
    Content-Type: text/html; charset=utf-8
    Content-Length: 207
    正文: <!doctype html> | <html lang=en> | <title>404 Not Found</title> | <h1>Not Found</h1> | <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>

上一篇:异常处理器的匹配顺序;下一篇:make_response() 的响应转换过程。

自定义描述与异常对象

实测 · 本机执行输出
   404 NOT FOUND | <!doctype html> | <html lang=en> | <title>404 Not Found</title> | <h1>Not Found</h1> | <p>文章 42 不存在</p>
  捕获到的异常: NotFound | code = 404 | name = Not Found | description = 文章 42 不存在

自带响应头的异常

实测 · 本机执行输出
  429: 429 TOO MANY REQUESTS | Retry-After = 30
  GET 一个只允许 POST 的路由: 405 METHOD NOT ALLOWED | Allow = OPTIONS, POST
  401: 401 UNAUTHORIZED | WWW-Authenticate = Basic realm=lab

传入 Response

实测 · 本机执行输出
  abort(Response(...)): 418 I'M A TEAPOT | 自定义响应体 | X-Why = 茶壶
  abort(redirect("/elsewhere")): 302 FOUND | Location = /elsewhere

abort 抛异常

实测 · 本机执行输出
  /after: 400 BAD REQUEST
  abort(498) → LookupError: no exception for 498

映射表与 aborter

实测 · 本机执行输出
  default_exceptions 共 31 个状态码;其中 4xx 25 个、5xx 6 个
  部分: {400: 'BadRequest', 401: 'Unauthorized', 403: 'Forbidden', 404: 'NotFound', 405: 'MethodNotAllowed', 409: 'Conflict', 410: 'Gone', 413: 'RequestEntityTooLarge', 415: 'UnsupportedMediaType', 418: 'ImATeapot', 422: 'UnprocessableEntity', 429: 'TooManyRequests', 500: 'InternalServerError', 501: 'NotImplemented', 503: 'ServiceUnavailable'}
  type(current_app.aborter) = Aborter | 是否是 app.aborter: True
  事先往 app.aborter.mapping 里注册了 499 之后,abort(499): 499 UNKNOWN | <!doctype html> | <html lang=en> | <title>499 Unknown Error</title> | <h1>Unknown Error</h1> | <p>客户

分步演示

abort()
本步的对象

    本文用到的工具与边界

    • 本机 macOS 27 arm64 / Python 3.14.7 / Flask 3.1.3 / Werkzeug 3.1.9 / Jinja2 3.1.6 / SQLAlchemy 2.1.1 / gunicorn 26.2.0(都装在自己的虚拟环境里);大多数实验用 Flask 的 test_client(直接调用 WSGI 应用,不经过网络),需要真实 HTTP 时另起 gunicorn 或开发服务器(端口 9600 以上,本机 127.0.0.1);计时用 time.perf_counter,数字每次运行会有小幅抖动
    • 没有验证:在蓝图与异步视图里 abort 的差别、HTTPException.get_response 的 environ 参数细节、4xx/5xx 之外(如 304、308 重定向)的异常类、自定义 aborter_class 的写法
    京ICP备2026067502号-1京公网安备11010502063487号