djc / askama

Type-safe, compiled Jinja-like templates for Rust
Apache License 2.0
3.48k stars 219 forks source link

How can askama::Error be encountered? #1096

Closed BBaoVanC closed 1 month ago

BBaoVanC commented 1 month ago

I am encountering some lifetime troubles related to my state when using askama_axum. Since it seems to just be boilerplate around rendering to String and returning that, I decided I'll try rendering the template to String in my axum handler function directly and returning that.

I see that the Template::render method returns a Result<String, askama::Error>. In what situation is Error returned here, instead of a compile time error? I can't understand what exactly askama_axum does to handle this error, so I can replicate that behavior in my own handler. Should I just be converting the askama::Error to a String and returning that String by itself if askama rendering errors?

djc commented 1 month ago

askama::Error can represent any error that happened during template rendering:

#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
    /// formatting error
    Fmt(fmt::Error),

    /// an error raised by using `?` in a template
    Custom(Box<dyn std::error::Error + Send + Sync>),

    /// json conversion error
    #[cfg(feature = "serde_json")]
    Json(::serde_json::Error),
}

In particular, because you can write custom filters or use trait implementations yielding custom errors (from TryFrom or TryInto implementations, for example). How you want to deal with those is up to you, but rendering the error into a String and wrapping some kind of error page/JSON structure around it is definitely a sensible way forward.