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

ds97pgxw  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(101)

我正在研究rust/actix/tera,不知道如何在actix输出中返回自定义的tera错误字符串。
下面是我的代码:

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...,而是想返回实际的tera错误,或者更好的是,在stderr输出中记录错误。

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

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

qyyhg6bp1#

正如在answer中所概述的,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))
        },
    }
}

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

> 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'

相关问题