如何在 Actix 中显示自定义 Tera 错误?

How to display custom Tera errors in Actix?

我正在研究 rust/actix/tera 并且不知道如何 return 在 actix 输出.

这是我的代码:

use actix_web::{App, get, error, Error, HttpResponse, HttpServer};
use tera::{Tera, Context};
use lazy_static::lazy_static;

lazy_static! {
    pub static ref TEMPLATES: Tera = {
        let mut tera = match Tera::new("templates/**/*") {
            Ok(t) => t,
            Err(e) => {
                println!("Template parsing error(s): {}", e);
                ::std::process::exit(1);
            }
        };
        tera.autoescape_on(vec!["html", ".sql"]);
        tera
    };
}

#[get("/")]
async fn tst() -> Result<HttpResponse, Error> {
    let mut ctx = Context::new();
    let title = String::from("Test");
    ctx.insert("title", &title);
    let body = TEMPLATES.render("index.html", &ctx)
        .map_err(|_| error::ErrorInternalServerError("some Tera error here..."))?;
    Ok(HttpResponse::Ok().body(body))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(tst)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

我不想得到 some Tera error here...,而是 return 实际的 tera 错误,或者更好的是,在 stderr 输出中另外记录错误。

[package]
name = "tst"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
actix-web = "3.3.2"
lazy_static = "1.4.0"
tera = "1.12.1"

如本 中所述,actix-web 提供了一整套用于转换错误的辅助函数,因此要达到预期效果,应将 get("/") 处理程序更改为如下:

#[get("/")]
async fn tst() -> Result<HttpResponse, Error> {
    let mut ctx = Context::new();
    let title = String::from("Test");
    ctx.insert("title", &title);
    match TEMPLATES.render("index.html", &ctx) {
        Ok(body) => Ok(HttpResponse::Ok().body(body)),
        Err(err) => {
            eprintln!("## Tera error: {}", err);
            Err(error::ErrorInternalServerError(err))
        },
    }
}

现在可以在服务器响应和进程中看到特定的 tera 错误字符串 stderr:

> curl -LsD- http://127.0.0.1:8080/
HTTP/1.1 500 Internal Server Error
content-length: 29
content-type: text/plain; charset=utf-8
date: Sat, 18 Sep 2021 18:28:14 GMT

Failed to render 'index.html'