Axum server - catching failure to bind to socket

I'm wondering if anyone who is familiar with axum web server knows about how to gracefully capture a failure to bind to a socket. I have the following code:

                    match axum::Server::bind(&addr)
                        .serve(app.into_make_service())
                        .await {
                            Ok(()) => (),
                            Err(e) => {
                                println!("failed to bind e={:?}", e));
                                std::process::exit(1);
                            }
                    }

My wish is for the error to be caught and then a graceful exit happens without a panic, however what I get is the bind() appears to be panicing before my Err(e) arm is reached.

Any ideas on how to make this work would be greatly appreciated!

There is a try_bind method on the Server struct that is re-exported from hyper. If you call try_bind instead of bind, you can then handle an error in the port-binding: Server in hyper::server - Rust

1 Like

Thank you very much!

Actually I should have mentioned I'm using the axum framework directly without axum-server. Am I correct that your suggestion requires using the axum-server crate?

I've yet to discover a need for axum-server, but perhaps I should explore that.

The suggestion works with axum. You can see here from the pub use hyper::Server; line that axum's Server struct is just hyper's Server struct re-exported.

Interesting. Thank you.