-
I want to send a custom message like |
Beta Was this translation helpful? Give feedback.
Answered by
jo-so
Mar 28, 2022
Replies: 2 comments 1 reply
-
You can use https://docs.rs/tower-http/latest/tower_http/catch_panic/index.html |
Beta Was this translation helpful? Give feedback.
1 reply
-
In the end, it's pretty easy, but you must know it: use std::{convert::Infallible, net::SocketAddr};
use hyper::{Body, Request, Response, Server, StatusCode};
use hyper::service::{make_service_fn, service_fn};
async fn handle(_: Request<Body>) -> Result<Response<Body>, Infallible> {
panic!("Test")
}
#[tokio::main]
async fn main() {
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let make_svc = make_service_fn(|_conn| async {
Ok::<_, Infallible>(service_fn(|req| {
async move {
use futures::FutureExt;
use std::panic::AssertUnwindSafe;
match AssertUnwindSafe(handle(req)).catch_unwind().await {
Ok(resp) => resp,
Err(_panic) => {
let mut resp = Response::new(Body::from("We are sorry"));
*resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
Ok(resp)
}
}
}
}))
});
let server = Server::bind(&addr).serve(make_svc);
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
seanmonstar
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In the end, it's pretty easy, but you must know it: