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

如何在纯Mako模板中排查NameError("Undefined")异常详情?

获取Mako模板NameError("Undefined")的详细信息

Mako默认抛出的NameError("Undefined")提示太简略,纯Mako环境下有两种办法拿到更多上下文信息:

1. 自定义Undefined类,直接增强错误提示

继承Mako自带的Undefined类,把变量名、模板上下文这些信息存下来,重写__str__方法抛出带详细信息的异常:

from mako.runtime import Undefined
from mako.exceptions import RichTraceback

class DetailedUndefined(Undefined):
    def __init__(self, name=None, context=None):
        self.var_name = name
        self.template_context = context
        super().__init__(name=name, context=context)

    def __str__(self):
        if self.template_context and self.var_name:
            tb = RichTraceback(context=self.template_context)
            error_msg = (
                f"未定义变量 '{self.var_name}' "
                f"在模板 '{tb.template_uri}' 的第 {tb.lineno} 行\n"
                f"代码片段:\n{''.join(tb.source_lines)}"
            )
            raise NameError(error_msg)
        return super().__str__()

用的时候,创建模板时指定undefined参数为这个自定义类就行:

from mako.template import Template

# 可以是字符串模板,也可以用Lookup加载本地模板文件
template = Template("欢迎, ${username}", undefined=DetailedUndefined)

try:
    template.render()  # 没传username变量,触发异常
except NameError as e:
    print(e)

2. 捕获异常后用RichTraceback解析详情

要是不想改Undefined类,也可以在捕获异常后,用Mako内置的RichTraceback类扒出模板位置、行号、出错代码片段这些信息:

from mako.template import Template
from mako.exceptions import RichTraceback

try:
    template = Template("欢迎, ${username}")
    template.render()
except Exception as e:
    tb = RichTraceback()
    print(f"错误位置:模板 '{tb.template_uri}' 第 {tb.lineno} 行")
    print(f"错误原因:{tb.error}")
    print("\n出错代码片段:")
    for line_num, line in zip(tb.linenos, tb.source_lines):
        print(f"{line_num:4d} | {line.rstrip()}")

这种方式不用改模板初始化的逻辑,只在异常处理的时候解析就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:31:40