【发布时间】:2020-07-15 16:58:14
【问题描述】:
使用warp.rs 0.2.2,让我们考虑一个基本的网络服务,其中GET / 有一个路由:
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let getRoot = warp::get().and(warp::path::end()).and_then(routes::getRoot);
warp::serve(getRoot).run(([0, 0, 0, 0], 3030)).await;
Ok(())
}
我的目标是在路由处理程序中使用? 进行错误处理,所以让我们在crate::routes 中编写一个可以出错并提前返回的函数:
use crate::errors::ServiceError;
use url::Url;
pub async fn getRoot() -> Result<impl warp::Reply, warp::Rejection> {
let _parsed_url = Url::parse(&"https://whydoesn.it/work?").map_err(ServiceError::from)?;
Ok("Hello world !")
}
此版本有效。
这里Url::parse() 返回的错误是url::ParseError
为了在错误类型之间进行转换,从url::ParseError 到ServiceError,然后从ServiceError 到warp::Rejection,我在crate::errors 中编写了一些错误助手:
#[derive(thiserror::Error, Debug)]
pub enum ServiceError {
#[error(transparent)]
Other(#[from] anyhow::Error), // source and Display delegate to anyhow::Error
}
impl warp::reject::Reject for ServiceError {}
impl From<ServiceError> for warp::reject::Rejection {
fn from(e: ServiceError) -> Self {
warp::reject::custom(e)
}
}
impl From<url::ParseError> for ServiceError {
fn from(e: url::ParseError) -> Self {
ServiceError::Other(e.into())
}
}
现在,上述方法有效,我正在尝试缩短第二个代码块以直接使用? 进行错误处理,并自动从底层错误(此处为url::ParseError)转换为warp::Rejection。
这是我尝试过的:
use crate::errors::ServiceError;
use url::Url;
pub async fn getRoot() -> Result<impl warp::Reply, ServiceError> {
let _parsed_url = Url::parse(&"https://whydoesn.it/work?")?;
Ok("Hello world !")
}
Url::Parse 返回的 url::ParseError 将转换为 ServiceError 以返回,但从我的处理程序返回 ServiceError 不起作用。
我得到的第一个编译错误是:
error[E0277]: the trait bound `errors::ServiceError: warp::reject::sealed::CombineRejection<warp::reject::Rejection>` is not satisfied
--> src/main.rs:102:54
|
102 | let getRoot = warp::get().and(warp::path::end()).and_then(routes::getRoot);
| ^^^^^^^^ the trait `warp::reject::sealed::CombineRejection<warp::reject::Rejection>` is not implemented for `errors::ServiceError`
有没有一种方法可以让我只使用? 来保持简短的错误处理:
- 使
ServiceError实现warp::reject::sealed::CombineRejection<warp::reject::Rejection>? - 解决这个问题?
【问题讨论】:
标签: http error-handling rust rust-warp