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

如何获取Tera模板渲染错误的行号及具体失败类型?

获取Tera模板渲染的详细错误信息

要获取包含行号和具体原因的详细错误信息,你可以通过以下两种方式处理Tera的错误:

方式一:使用Debug格式化输出错误

Tera的TeraError类型的Debug实现会包含完整的错误细节,包括行号、列号和具体错误描述。只需将错误格式化时的{}改为{:?}:

let mut context = Context::new();
context.insert("adminform", &admin_form);
let html = match tera.render("change_form.html", &context) {
    Ok(html) => html,
    Err(err) => return HttpResponse::InternalServerError().body(format!("Failed to render the template: {:?}", err))
};

输出的错误信息会类似:

Failed to render the template: Render(TemplateError { name: Some("change_form.html"), line: Some(15), column: Some(8), message: "Variable 'username' not found in context", source: None })

方式二:手动提取错误字段(定制化输出)

你可以匹配TeraError的变体,直接提取行号、列号和错误信息,输出更规整的内容:

use tera::{Context, Tera, TeraError};

// ... 其他代码 ...

let mut context = Context::new();
context.insert("adminform", &admin_form);
let html = match tera.render("change_form.html", &context) {
    Ok(html) => html,
    Err(err) => {
        let error_msg = match err {
            TeraError::Render(template_err) => {
                format!(
                    "Template render error in '{}' at line {} column {}: {}",
                    template_err.name.unwrap_or("unknown template"),
                    template_err.line.unwrap_or(0),
                    template_err.column.unwrap_or(0),
                    template_err.message
                )
            }
            other_err => format!("Unexpected error: {:?}", other_err),
        };
        return HttpResponse::InternalServerError().body(error_msg);
    }
};

这种方式可以根据需求自定义错误信息的格式,让调试更直观。

为什么原错误信息简略?

Tera的TeraError实现了Display trait,默认输出的是简化的用户友好提示;而Debug trait的实现才会暴露开发者需要的调试细节,包括模板位置和具体错误原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:22:43