Better minijinja Error Messages
May 2024
-
Add
debug to the Cargo.toml dependency
-
Use
:# in the error message strings
---
[dependencies]
minijinja = { version= "2.12.0", features = ["debug", "loader"] }
---
use minijinja::{Environment, context};
fn main() {
let mut env = Environment::new();
env.set_debug(true);
env.add_template_owned(
"hello", "{% include 'asdf' %}".to_string()
).unwrap();
let template = env.get_template("hello").unwrap();
match template.render(context!(name => "World")) {
Ok(output) => println!("{}", output),
Err(err) => {
eprintln!("{}", error_html(&err));
}
}
}
pub fn error_text(err: &minijinja::Error) -> String {
let mut output = vec!["A MiniJinja error occurred\n".to_string()];
output.push(format!("Could not render template:\n{:#}", err));
let mut err = &err as &dyn std::error::Error;
while let Some(next_err) = err.source() {
output.push(format!("\ncaused by:\n{:#}", next_err));
err = next_err;
}
output.join("\n")
}
pub fn error_html(err: &minijinja::Error) -> String {
let mut output = vec![
r#"<html><head><style>body { background-color: black; color: goldenrod; }</style></head><body><pre>"#.to_string()
];
output.push(
"A MiniJinja error occurred\n".to_string(),
);
output.push(format!(
"Could not render template:\n{:#}</p>",
err
));
let mut err = &err as &dyn std::error::Error;
while let Some(next_err) = err.source() {
output.push(format!(
"\ncaused by:\n{:#}",
next_err
));
err = next_err;
}
output.push("</pre></body></html>".to_string());
output.join("\n")
}
<html><head><style>body {{ background-color: black; color: goldenrod; }}</style></head><body><pre>
A MiniJinja error occurred
Could not render template:
template not found: tried to include non-existing template "asdf" (in hello:1)
------------------------------------ hello ------------------------------------
1 > {% include 'asdf' %}
i ^^^^^^^^^^^^^^ template not found
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
No referenced variables
-------------------------------------------------------------------------------</p>
</pre></body></html>