You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sanic应用如何捕获所有无效端点并返回404状态?

如何在Sanic中捕获无效端点请求并返回404状态?

问题场景

我有一段Sanic Python应用代码,定义了如下路由:

def create_inspector(app):
    inspector = Sanic(configure_logging=False)
    inspector.config['KEEP_ALIVE'] = False
    inspector.app = app
    inspector.add_route(render_status, '/')
    inspector.add_route(get_status, '/api/status')
    return inspector

当通过以下命令访问未定义的端点时:

curl -k http://localhost:9504/api/123

应用日志中出现了如下回溯信息:

File "/opt/product/4.0.0.1/lib64/python3.6/site-packages/sanic/app.py", line 546, in handle_request
    handler, args, kwargs, uri = self.router.get(request)
  File "/opt/product/4.0.0.1/lib64/python3.6/site-packages/sanic/router.py", line 344, in get
    return self._get(request.path, request.method, '')
  File "/opt/product/4.0.0.1/lib64/python3.6/site-packages/sanic/router.py", line 393, in _get
    raise NotFound('Requested URL {} not found'.format(url))
sanic.exceptions.NotFound: Requested URL /api/123 not found

希望捕获所有无效端点的请求,并返回404(资源未找到)状态。

解决方案

当然可以实现,Sanic提供了全局异常处理机制来捕获NotFound异常,自定义返回内容的同时避免日志输出冗余回溯信息。以下是两种常用实现方式:

方式一:使用@app.exception装饰器

在创建inspector实例后,添加针对NotFound异常的处理函数:

from sanic.exceptions import NotFound
from sanic.response import json

def create_inspector(app):
    inspector = Sanic(configure_logging=False)
    inspector.config['KEEP_ALIVE'] = False
    inspector.app = app
    
    # 捕获NotFound异常并返回自定义404响应
    @inspector.exception(NotFound)
    async def handle_not_found(request, exception):
        return json({"error": "资源未找到"}, status=404)
    
    inspector.add_route(render_status, '/')
    inspector.add_route(get_status, '/api/status')
    return inspector

方式二:自定义全局错误处理器

通过继承ErrorHandler类,统一管理所有异常类型,针对性处理NotFound:

from sanic.exceptions import NotFound
from sanic.handlers import ErrorHandler
from sanic.response import json

class CustomErrorHandler(ErrorHandler):
    def default(self, request, exception):
        if isinstance(exception, NotFound):
            return json({"error": "资源未找到"}, status=404)
        # 其他异常沿用默认处理逻辑
        return super().default(request, exception)

def create_inspector(app):
    inspector = Sanic(configure_logging=False)
    inspector.config['KEEP_ALIVE'] = False
    inspector.app = app
    # 替换为自定义错误处理器
    inspector.error_handler = CustomErrorHandler()
    
    inspector.add_route(render_status, '/')
    inspector.add_route(get_status, '/api/status')
    return inspector

配置完成后,访问未定义端点时应用会返回标准的404响应,日志中也不会再输出完整的回溯堆栈信息。


内容的提问来源于stack exchange,提问作者vector8188

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 13:55:16