2

我正在研究rust//并且无法弄清楚如何在输出actix中返回自定义错误字符串。terateraactix

这是我的代码:

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"

# 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"
4

1 回答 1

0

正如在这个答案中所概述的那样,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'
于 2021-09-18T18:36:56.953 回答