【问题标题】:How to display custom Tera errors in Actix?如何在 Actix 中显示自定义 Tera 错误?
【发布时间】:2021-11-10 19:53:24
【问题描述】:

我正在研究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
}

我想返回实际的tera 错误,而不是得到some Tera error here...,或者更好的是,另外在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"

【问题讨论】:

  • 听起来像是anyhow
  • 您能详细说明一下吗?我尝试使用您建议的 crate,但由于一些错误而卡住了,我无法解决。

标签: rust actix-web rust-actix tera


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    相关资源
    最近更新 更多