Skip to content

How to send a custom response on panic #2793

Answered by jo-so
jo-so asked this question in Q&A
Discussion options

You must be logged in to vote

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 {

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@jo-so
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by seanmonstar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants