【发布时间】:2018-10-31 09:40:14
【问题描述】:
我正在尝试使用 hyper 创建一个 REST 服务器。对于强大的错误处理,我希望服务返回一个包含超、柴油和其他错误的自定义错误类型的未来。不幸的是,hyper::Response 似乎硬编码了错误类型为hyper::error::Error 的流,这与我为我的服务定义的错误类型冲突。我看到了几个可能的解决方案:
通过修改
hyper::Response让我的服务返回我的自定义错误类型,这似乎很难。在
hyper::error::Error中包装非超错误。这看起来很老套。别的东西。看来我错过了执行此操作的“正确”方法。
以下代码显示了我想我想做的事情:
extern crate diesel;
extern crate futures;
extern crate hyper;
use futures::future::{ok, Future};
use hyper::StatusCode;
use hyper::server::{Request, Response, Service};
fn main() {
let address = "127.0.0.1:8080".parse().unwrap();
let server = hyper::server::Http::new()
.bind(&address, move || Ok(ApiService {}))
.unwrap();
server.run().unwrap();
}
pub struct ApiService;
impl Service for ApiService {
type Request = Request;
type Response = Response;
type Error = Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, request: Request) -> Self::Future {
Box::new(ok(Response::new().with_status(StatusCode::Ok)))
}
}
#[derive(Debug)]
pub enum Error {
Request(hyper::Error),
DatabaseResult(diesel::result::Error),
DatabaseConnection(diesel::ConnectionError),
Other(String),
}
// omitted impl of Display, std::error::Error for brevity
此代码导致编译器错误,我认为这是因为bind 函数要求响应类型的主体是错误类型为hyper::error::Error 的流:
error[E0271]: type mismatch resolving `<ApiService as hyper::client::Service>::Error == hyper::Error`
--> src/main.rs:14:10
|
14 | .bind(&address, move || Ok(ApiService {}))
| ^^^^ expected enum `Error`, found enum `hyper::Error`
|
= note: expected type `Error`
found type `hyper::Error`
【问题讨论】: