Sanic 异常处理完全指南:从内置异常到自定义错误响应

原创2026-09-20 20:34:581,760 阅读
文章标签:后端Web框架

Sanic 异常处理完全指南:从内置异常到自定义错误响应

本文围绕 Sanic 框架的异常体系展开,系统讲解如何使用 SanicException 及其子类中断请求处理流程、为异常附加状态码/头信息/上下文数据、通过 @app.exception 与自定义 ErrorHandler 接管错误响应,以及如何利用 HTML/Text/JSON 三种内置回退格式与 report_exception 信号接入 Sentry 等第三方错误上报服务。读完本文,你将掌握一套从抛出异常到生产级错误呈现与上报的完整实战方案,本文对应官方文档位于 guide/content/en/guide/best-practices/exceptions.md。

使用 Sanic 内置异常中断处理流程

在编写 Web 应用时,经常会遇到"需要立即停止当前 handler 的执行,并向客户端返回一个特定状态码响应"的场景。Sanic 为此提供了 SanicException:只要在请求处理过程中抛出它,Sanic 会自动完成剩余工作——生成对应的 HTTP 响应,而不是让整个进程崩溃。

from sanic.exceptions import SanicException

@app.route("/youshallnotpass")
async def no_no(request):
    raise SanicException("Something went wrong.", status_code=501)

SanicException 接受一个可选的 status_code 参数;不传时默认返回 500(Internal Server Error)。这一点可以在源码中得到印证:在 sanic/exceptions.py 中,类的默认定义为 status_code: int = 500,而构造函数的实现(sanic/exceptions.py)会将传入的 message、status_code、quiet、context、extra、headers 统一解析并挂到实例上。

常用的标准异常

Sanic 提供了大量标准异常类,它们各自绑定了合适的 HTTP 状态码,抛出后无需再手动指定。官方文档建议在业务代码中优先自行实现以下常见异常:

异常类 状态码 语义
BadRequest 400 客户端请求不合法
Unauthorized 401 未认证
Forbidden 403 无权限
NotFound 404 资源不存在
ServerError 500 服务器内部错误

实际使用示例如下:

from sanic import exceptions

@app.route("/login")
async def login(request):
    user = await some_login_func(request)
    if not user:
        raise exceptions.NotFound(
            f"Could not find user with username={request.json.username}"
        )

从 sanic/exceptions.py 的源码可以看到,NotFound 默认 status_code = 404、quiet = True,BadRequest 默认 status_code = 400、quiet = True。此外该模块还提供了 MethodNotAllowed(405)、ServiceUnavailable(503)、PayloadTooLarge(413)、RequestTimeout(408)、RangeNotSatisfiable(416) 等异常类,并给出了 InvalidUsage = BadRequest、InternalServerError = ServerError、MethodNotSupported = MethodNotAllowed 等别名,方便不同习惯的开发者调用。需要特别注意的是,像 RequestTimeout、PayloadTooLarge 这类异常在文档注释中被明确标注为"Sanic 内部抛出、不应直接使用",业务代码应优先使用面向业务的异常类。

异常属性:让错误响应更加可控

Sanic 中所有异常都继承自 SanicException,该基类提供了一组属性,帮助开发者在整个应用中保持一致、可预测的异常输出方式:

  • message:异常消息文本
  • status_code:响应状态码
  • quiet:是否抑制错误日志输出
  • headers:附加到响应上的 HTTP 头
  • context:始终发送给客户端的上下文数据
  • extra:仅在开发模式下展示、生产环境隐藏的附加元数据

这些属性都可以在创建异常实例时作为参数传入;其中前三个(message、status_code、quiet)还可以直接定义为类变量,从而实现异常类型的"模板化"。

message:类级别定义,统一文案

message 控制展示给调用方的消息文本。最有价值的一点是:你可以在自定义异常类的定义体上直接设置 message,从而在全应用范围内统一错误措辞。

class CustomError(SanicException):
    message = "Something bad happened"

raise CustomError
# 或
raise CustomError("Override the default message with something else")

从 sanic/exceptions.py 的实现看,当实例化时未传 message,构造函数会取类属性 self.message;如果连类属性也是空,则会从 STATUS_CODES 映射中取状态码对应的标准 HTTP 短语作为消息。

status_code:自定义 4xx/5xx 状态码

该属性用于决定异常被抛出后响应中的状态码,特别适合创建针对"客户端传入非法数据"的 400 系列自定义异常。

class TeapotError(SanicException):
    status_code = 418
    message = "Sorry, I cannot brew coffee"

raise TeapotError
# 或
raise TeapotError(status_code=400)

需要注意的是,实例化时传入的 status_code 会覆盖类变量(sanic/exceptions.py 中通过 status_code or getattr(self.__class__, "status_code", None) 完成优先级处理),所以上面的 raise TeapotError(status_code=400) 最终返回的是 400。

quiet:控制错误日志输出

默认情况下,异常会被 Sanic 输出到 error_logger。如果你只是用异常来触发异常处理器中的某些逻辑(而不是真正需要告警),可以通过 quiet=True 抑制日志,避免日志噪音。

class SilentError(SanicException):
    message = "Something happened, but not shown in logs"
    quiet = True

raise SilentError
# 或
raise InvalidUsage("blah blah", quiet=True)

这条逻辑在 sanic/handlers/error.py 的 ErrorHandler.log 静态方法中体现得很清楚:quiet = getattr(exception, "quiet", False),只有当 quiet is False 或全局配置 NOISY_EXCEPTIONS 为 True 时才调用 error_logger.exception(...)。

另外,调试期间如果想"无视所有 quiet=True",可以全局开启 NOISY_EXCEPTIONS 配置(该配置项在 sanic/config.py 中默认值为 False,v21.12 加入):

app.config.NOISY_EXCEPTIONS = True

headers:直接从异常控制响应头

把 SanicException 当作响应构造工具是非常强大的用法——你不仅可以通过 status_code 控制状态码,还可以通过 headers 直接控制响应头:

class MyException(SanicException):
    headers = {
      "X-Foo": "bar"
    }

raise MyException
# 或
raise InvalidUsage("blah blah", headers={
    "X-Foo": "bar"
})

源码中 Unauthorized 异常正是利用了这一机制:当传入 scheme 参数时,它会在 __init__ 中把 WWW-Authenticate 头合并进 self.headers(见 sanic/exceptions.py)。MethodNotAllowed 也会自动追加 Allow 头(sanic/exceptions.py)。

extra 与 context:附加运行时数据

extra 与 context 均为 v21.12 新增能力,具体差异见下文"上下文异常"章节:

raise SanicException(..., extra={"name": "Adam"})
raise SanicException(..., context={"foo": "bar"})

异常处理:接管错误响应

Sanic 默认会自动渲染错误页,因此在大多数场景下你无需自行处理。但如果你希望对异常发生后的响应有更多控制,可以实现自己的处理器。Sanic 为此提供了装饰器,它不仅能处理 Sanic 标准异常,还能处理应用可能抛出的任何异常。

使用 @app.exception() 注册处理器

最简单的方式是把一个或多个异常类型传给 @app.exception():

from sanic.exceptions import NotFound

@app.exception(NotFound, SomeCustomException)
async def ignore_404s(request, exception):
    return text("Yep, I totally found the page: {}".format(request.url))

处理器函数接收 (request, exception) 两个参数,返回值会直接作为 HTTP 响应返回给客户端。该装饰器的底层实现在 sanic/mixins/exceptions.py:它会构造一个 FutureException 存入 _future_exceptions 集合,并在 apply=True(默认)时立即注册到应用;当用于 Blueprint 时,处理器只对该蓝图下的路由生效——因此像 NotFound 这类通用异常应注册在应用实例上,而不是蓝图上。同时该模块还提供了便捷方法 all_exceptions(sanic/mixins/exceptions.py),等价于 @app.exception(Exception)。

Catchall 处理器

你也可以通过捕获 Exception 来创建一个兜底处理器:

@app.exception(Exception)
async def catch_anything(request, exception):
    ...

通过 error_handler.add() 添加处理器

除了装饰器,还可以直接调用 app.error_handler.add():

async def server_error_handler(request, exception):
    return text("Oops, server error", status=500)

app.error_handler.add(Exception, server_error_handler)

ErrorHandler.add 的实现位于 sanic/handlers/error.py,它支持可选的 route_names 参数将处理器限定到指定路由。其内部使用 cached_handlers 字典做缓存加速查找(lookup 方法会遍历异常类的 MRO 链寻找匹配的注册项,见 sanic/handlers/error.py);如果在同一路由、同一异常类型上重复注册,会直接抛出 ServerError 提示重复定义(sanic/handlers/error.py)。

内置错误格式与 per-route 控制

Sanic 内置了三种异常响应格式:HTML、JSON、Text,具体效果可参考下文"回退处理器"一节的示例。你可以在每条路由级别通过 error_format 关键字参数控制使用哪种格式(该能力在 v21.9 加入):

@app.request("/", error_format="text")
async def handler(request):
    ...

从 sanic/mixins/routes.py 可以看到,当 error_format 未指定或为 "auto" 时,Sanic 会通过 _determine_error_format(handler) 分析 handler 源码中返回的响应类型来推断格式(例如返回 json() 则推断为 JSON,返回 text() 则推断为 Text,对应关系定义在 sanic/errorpages.py 的 RESPONSE_MAPPING 中)。此外 errorpages.guess_mime(sanic/errorpages.py)会综合考虑路由的 error_format、全局 FALLBACK_ERROR_FORMAT 以及请求的 Accept 头来决定最终的 MIME 类型。

自定义错误处理器

某些场景下,你希望给默认错误处理增加更多功能,此时可以继承 Sanic 的默认 ErrorHandler,重写 default 方法:

from sanic.handlers import ErrorHandler

class CustomErrorHandler(ErrorHandler):
    def default(self, request: Request, exception: Exception) -> HTTPResponse:
        ''' handles errors that have no error handlers assigned '''
        # You custom error handling logic...
        status_code = getattr(exception, "status_code", 500)
        return json({
          "error": str(exception),
          "foo": "bar"
        }, status=status_code)

app.error_handler = CustomErrorHandler()

ErrorHandler 的核心职责在 sanic/handlers/error.py 的类文档中写明:它处理所有未捕获的异常,并支持开发者扩展以完成记录错误统计、上报到外部实时告警系统等任务。response 方法(sanic/handlers/error.py)会先查找已注册的 handler,找不到则回退到 default;如果 handler 自身抛出了异常,调试模式下返回"异常发生在异常处理器中"的 500 文本,生产模式下则返回通用提示。default 方法(sanic/handlers/error.py)会先写日志,再根据 FALLBACK_ERROR_FORMAT 调用 exception_response 渲染响应。除了直接赋值 app.error_handler,也可以在创建应用时传入:Sanic("MyApp", error_handler=CustomErrorHandler())(见 default 方法 docstring 中的示例)。

回退处理器(Fallback Handler)

Sanic 提供三种回退异常处理器:HTML、Text、JSON。它们展示的详细程度取决于应用是否处于调试模式(详见 guide/content/en/guide/running/development.md)。默认情况下 Sanic 处于 "auto" 模式:它会根据传入请求和可能匹配的 handler 自动选择合适的响应格式——例如浏览器访问时总是返回 HTML 错误页,使用 curl 时则可能返回 JSON 或纯文本。

HTML

app.config.FALLBACK_ERROR_FORMAT = "html"

调试模式(app.config.DEBUG = True)下会渲染包含完整堆栈信息的错误页面:

Sanic HTML 错误页(调试模式,展示完整堆栈跟踪)

生产模式(app.config.DEBUG = False)下只显示简洁的通用错误信息,避免泄露内部实现细节:

Sanic HTML 错误页(生产模式,仅显示通用错误信息)

Text

app.config.FALLBACK_ERROR_FORMAT = "text"

调试模式下,用 curl localhost:8000/exc -i 请求会看到包含完整 traceback 的纯文本响应:

HTTP/1.1 500 Internal Server Error
content-length: 620
connection: keep-alive
content-type: text/plain; charset=utf-8

⚠️ 500 — Internal Server Error
==============================
That time when that thing broke that other thing? That happened.

ServerError: That time when that thing broke that other thing? That happened. while handling path /exc
Traceback of TestApp (most recent call last):

  ServerError: That time when that thing broke that other thing? That happened.
    File /path/to/sanic/app.py, line 979, in handle_request
    response = await response

    File /path/to/server.py, line 16, in handler
    do_something(cause_error=True)

    File /path/to/something.py, line 9, in do_something
    raise ServerError(

生产模式下则只返回一行精简消息:

HTTP/1.1 500 Internal Server Error
content-length: 134
connection: keep-alive
content-type: text/plain; charset=utf-8

⚠️ 500 — Internal Server Error
==============================
That time when that thing broke that other thing? That happened.

Text 渲染器的实现对应 sanic/errorpages.py 中的 TextRenderer:full 模式会遍历 sys.exc_info() 的异常链并格式化每一帧的 File/line/in 信息,同时按需输出 context(始终显示)和 extra(仅 full 模式显示)两个对象。

JSON

app.config.FALLBACK_ERROR_FORMAT = "json"

调试模式下返回包含 path、args 以及结构化 exceptions 帧信息的 JSON:

HTTP/1.1 500 Internal Server Error
content-length: 572
connection: keep-alive
content-type: application/json

{
  "description": "Internal Server Error",
  "status": 500,
  "message": "That time when that thing broke that other thing? That happened.",
  "path": "/exc",
  "args": {},
  "exceptions": [
    {
      "type": "ServerError",
      "exception": "That time when that thing broke that other thing? That happened.",
      "frames": [
        {
          "file": "/path/to/sanic/app.py",
          "line": 979,
          "name": "handle_request",
          "src": "response = await response"
        },
        {
          "file": "/path/to/server.py",
          "line": 16,
          "name": "handler",
          "src": "do_something(cause_error=True)"
        },
        {
          "file": "/path/to/something.py",
          "line": 9,
          "name": "do_something",
          "src": "raise ServerError("
        }
      ]
    }
  ]
}

生产模式下返回最小化结构:

HTTP/1.1 500 Internal Server Error
content-length: 129
connection: keep-alive
content-type: application/json

{
  "description": "Internal Server Error",
  "status": 500,
  "message": "That time when that thing broke that other thing? That happened."
}

JSON 渲染逻辑在 sanic/errorpages.py 的 JSONRenderer._generate_output 中:基础字段固定为 description、status、message,context 始终附加、extra 仅在 full 模式下附加;full 模式下额外输出 path、args 与逐帧的 exceptions 列表,且优先使用 ujson(若已安装)进行序列化(sanic/errorpages.py)。

Auto

Sanic 还提供"自动猜测"回退格式的选项:

app.config.FALLBACK_ERROR_FORMAT = "auto"

auto 是默认值(见 sanic/errorpages.py 的 DEFAULT_FORMAT = "auto" 与 sanic/config.py 中的配置校验逻辑)。guess_mime 会按照"路由 error_format → 全局 FALLBACK_ERROR_FORMAT → 请求 Accept 头/content-type"的顺序依次推断,最终把 MIME 类型映射到对应的 TextRenderer / JSONRenderer / HTMLRenderer(映射表见 sanic/errorpages.py)。

上下文异常(Contextual Exceptions)

默认的异常消息(如类级别固定的 message)无法满足两个诉求:

  1. 动态且可预测的消息格式
  2. 向错误消息附加额外上下文

该能力在 v21.12 加入。使用 Sanic 的异常,你可以通过两种方式在运行时提供附加信息:

raise TeapotError(extra={"foo": "bar"}, context={"foo": "bar"})

两者的区别与选用时机如下:

  • extra —— 该对象永远不会发送给生产环境客户端,仅限内部使用。典型用途包括:
    • 生成动态错误消息(见下例)
    • 为日志器提供运行时细节
    • 调试信息(开发模式下渲染展示)
  • context —— 该对象始终发送给生产环境客户端,一般用于传达"发生了什么"的额外细节。典型用途包括:
    • 在 BadRequest 校验失败时提供可选的替代值
    • 为客户的工单提供有用的排查细节
    • 展示当前登录用户等状态信息

用 extra 生成动态且可预测的消息

Sanic 异常可以通过 extra 关键字参数为异常实例附加额外信息:

class TeapotError(SanicException):
    status_code = 418

    @property
    def message(self):
        return f"Sorry {self.extra['name']}, I cannot make you coffee"

raise TeapotError(extra={"name": "Adam"})

注意:这里 message 被定义为属性(property),因此每次访问都会基于 self.extra 动态计算。extra 信息对象在 PRODUCTION 模式下会被抑制,在 DEVELOPMENT 模式下才会展示:

Sanic 开发模式下 extra 附加信息渲染效果

Sanic 生产模式下 extra 附加信息被抑制

从渲染器源码看,这一行为由 BaseRenderer.render 中的 self.debug and not getattr(self.exception, "quiet", False) 控制选择 full 还是 minimal 输出(sanic/errorpages.py),而 extra 只在 full(调试)模式下被附加到响应中。

用 context 向错误消息附加上下文

Sanic 异常还可以通过 context 参数把"想让用户知道的信息"随异常一起传递,这在构建微服务或 JSON 格式 API 时特别有用——除了可解析的错误消息之外,还能向客户端返回额外的上下文细节:

raise TeapotError(context={"foo": "bar"})

这是你希望始终随错误一起传递的信息(只要可用)。PRODUCTION 模式下响应如下:

{
  "description": "I'm a teapot",
  "status": 418,
  "message": "Sorry Adam, I cannot make you coffee",
  "context": {
    "foo": "bar"
  }
}

DEVELOPMENT 模式下则会额外包含 path、args 与堆栈帧信息:

{
  "description": "I'm a teapot",
  "status": 418,
  "message": "Sorry Adam, I cannot make you coffee",
  "context": {
    "foo": "bar"
  },
  "path": "/",
  "args": {},
  "exceptions": [
    {
      "type": "TeapotError",
      "exception": "Sorry Adam, I cannot make you coffee",
      "frames": [
        {
          "file": "handle_request",
          "line": 83,
          "name": "handle_request",
          "src": ""
        },
        {
          "file": "/tmp/p.py",
          "line": 17,
          "name": "handler",
          "src": "raise TeapotError("
        }
      ]
    }
  ]
}

错误上报:接入 Sentry / Rollbar

Sanic 提供了一条内置信号(参见 guide/content/en/guide/advanced/signals.md 的"内置信号"章节),允许你挂接到异常上报流程中。这在需要把异常信息发送给 Sentry、Rollbar 等第三方服务时非常有用,只需挂载一个上报处理器即可:

@app.report_exception
async def catch_any_exception(app: Sanic, exception: Exception):
    print("Caught exception:", exception)

注意:该处理器会被调度到后台任务中执行,不应用于修改任何响应数据。它只用于日志或上报目的,不应影响应用向客户端返回错误响应的能力。

report_exception 在 sanic/app.py 中实现,其本质是 @app.signal(Event.SERVER_EXCEPTION_REPORT) 的便捷封装——它把 (app, exception) 形式的处理器包装为 (exception) 形式并注册到内置信号 SERVER_EXCEPTION_REPORT 上。该能力在 v23.6 加入。由于上报逻辑运行在后台任务中,即便上报服务响应缓慢或超时,也不会阻塞错误响应的返回。

小结

Sanic 的异常体系覆盖了从"抛出即响应"的内置异常、可模板化的属性设计(message/status_code/quiet/headers),到灵活的处理器注册(@app.exception、app.error_handler.add()、自定义 ErrorHandler 子类),再到自动协商的三种回退渲染格式与 extra/context 上下文机制,最后以信号化的 report_exception 打通外部错误上报链路。推荐组合使用方式:业务代码中抛出带语义的 SanicException 子类(必要时携带 context 与 extra),通过 @app.exception 处理关键业务异常,继承 ErrorHandler 统一兜底,并用 report_exception 接入监控平台,即可构建一套完整、一致且可观测的错误处理体系。

登录后查看全文
sanic