Continuing the discussion from Answering HTTP requests:
I've been looking into hyper
. I'm currently facing the problem that errors don't get reported.
This is my test setup:
Cargo.toml
:
[dependencies]
tokio = { version = "1", features = ["full"] }
hyper = { version = "0.14", features = ["http1", "http2", "server", "runtime", "tcp", "deprecated"] }
anyhow = { version = "1", features = ["backtrace"] }
src/main.rs
:
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Response, Server};
use std::net::{Ipv6Addr, SocketAddr};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let addr = SocketAddr::from((Ipv6Addr::LOCALHOST, 3000));
let make_svc = make_service_fn(move |_conn| async move {
Ok::<_, anyhow::Error>(service_fn(move |_req| async move {
anyhow::bail!("Test");
#[allow(unreachable_code)]
Ok::<Response<Body>, anyhow::Error>(unreachable!())
}))
});
Server::bind(&addr).serve(make_svc).await?;
Ok(())
}
If I access the server with a webbrowser, the webbrowser reports a connection reset and stdout of the server process doesn't report anything at all.
% cargo run
Compiling http-error v0.1.0 (/usr/home/jbe/rust-experiment/http-error)
Finished dev [unoptimized + debuginfo] target(s) in 0.40s
Running `target/debug/http-error`
And in a separate process:
% curl -i http://localhost:3000/
curl: (52) Empty reply from server
What can I do to enable error reporting or retrieve the anyhow::Error
somewhere?
I found a workaround, but I'm not really happy with it and don't believe this is the idiomatic way to handle this:
use anyhow::Context as _;
async fn handler(_req: Request<Body>) -> anyhow::Result<Response<Body>> {
anyhow::bail!("Test");
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let addr = SocketAddr::from((Ipv6Addr::LOCALHOST, 3000));
let make_svc = make_service_fn(move |_conn| async move {
Ok::<_, anyhow::Error>(service_fn(move |req| async move {
match handler(req).await.context("error in handler") {
Ok(res) => Ok(res),
Err(err) => {
eprintln!("#### ERROR #### {err:?}\n");
Err(err)
}
}
}))
});
Server::bind(&addr).serve(make_svc).await?;
Ok(())
}