首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将tera::Error转换为actix_web::Error?

如何将tera::Error转换为actix_web::Error?
EN

Stack Overflow用户
提问于 2021-09-16 21:24:28
回答 1查看 380关注 0票数 1

我正在学习rust/actix/tera,不知道如何在tera::Error上实现ResponseError特性,或者如何将tera::Error转换为actix_web::Error

使用以下代码片段:

代码语言:javascript
复制
match TEMPLATES.render("index.html", &ctx) {
    Ok(s) => Ok(HttpResponse::Ok().body(s)),
    Err(e) => Err(e),
}

我收到一个错误:

代码语言:javascript
复制
mismatched types

expected struct `actix_web::Error`, found struct `tera::Error`rustc(E0308)
main.rs(71, 23): expected struct `actix_web::Error`, found struct `tera::Error`

因此,我尝试了以下几点:

代码语言:javascript
复制
match TEMPLATES.render("index.html", &ctx) {
    Ok(s) => Ok(HttpResponse::Ok().body(s)),
    Err(e) => Err(e.into()),
}

但在这种情况下我得到:

代码语言:javascript
复制
the trait bound `tera::Error: actix_web::ResponseError` is not satisfied

the trait `actix_web::ResponseError` is not implemented for `tera::Error`

note: required because of the requirements on the impl of `std::convert::From<tera::Error>` for `actix_web::Error`
note: required because of the requirements on the impl of `std::convert::Into<actix_web::Error>` for `tera::Error`rustc(E0277)
main.rs(71, 25): the trait `actix_web::ResponseError` is not implemented for `tera::Error`

所以我终于尝试了:

代码语言:javascript
复制
use actix_web::{get, post, web, error, Error, ResponseError,
    HttpRequest, HttpResponse, HttpServer,
    App, Responder};
use tera::{Tera, Context};
use tera;

impl ResponseError for tera::Error {}

但现在:

代码语言:javascript
复制
only traits defined in the current crate can be implemented for arbitrary types

impl doesn't use only types from inside the current crate

note: define and implement a trait or new type insteadrustc(E0117)
main.rs(12, 1): impl doesn't use only types from inside the current crate
main.rs(12, 24): `tera::Error` is not defined in the current crate

具有match块的函数签名如下:

代码语言:javascript
复制
#[get("/")]
async fn tst() -> Result<HttpResponse, Error> {}

我做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-18 08:00:11

正如您已经发现的,不能使用into()tera::Error转换为actix_web::Error,因为没有直接定义这种转换。在这种情况下,它会给出一个稍微误导人的错误--因为存在这种转换:

代码语言:javascript
复制
impl<T> From<T> for Error
where
    T: 'static + ResponseError, 

编译器抛出一个错误,说明只要tera错误实现了ResponseError,它就可以进行转换。但是你不能让它实现这个特性,因为“特征孤儿法则”,它说你不能从你自己的板条箱外实现一个特性到你自己的板条箱之外的一个类型。

您可以将tera::Error包装在自己的结构中,然后将ResponseError实现为这个问题概述了

但是有一个更简单的解决方案:actix提供了一个用于转换错误的整个辅助函数,您可以这样使用:

代码语言:javascript
复制
match TEMPLATES.render("index.html", &ctx) {
    Ok(s) => Ok(HttpResponse::Ok().body(s)),
    Err(e) => Err(error::ErrorInternalServerError(e)),
}

提供的帮助程序将提供的错误映射到指定的HTTP响应代码中,因此您可以选择一个最接近于表示所发生的错误的错误。

还请参阅actix 错误处理文档

警告:这个解决方案是未经测试的,我从未使用过teraactix-web,而是从浏览他们的文档中收集到的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69215352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档