From 29a04c8d747945bb9a66793fdc87288845e4c716 Mon Sep 17 00:00:00 2001 From: sigoden Date: Sun, 12 Mar 2023 15:20:40 +0800 Subject: [PATCH] refactor: improve error handle (#195) --- src/args.rs | 4 ++-- src/main.rs | 19 ++++++------------- src/tls.rs | 11 +++++------ src/utils.rs | 4 ++-- tests/tls.rs | 4 ++-- 5 files changed, 17 insertions(+), 25 deletions(-) diff --git a/src/args.rs b/src/args.rs index 44ab591..48c9afa 100644 --- a/src/args.rs +++ b/src/args.rs @@ -1,4 +1,4 @@ -use anyhow::{anyhow, bail, Result}; +use anyhow::{bail, Context, Result}; use clap::builder::PossibleValuesParser; use clap::{value_parser, Arg, ArgAction, ArgMatches, Command}; use clap_complete::{generate, Generator, Shell}; @@ -380,7 +380,7 @@ impl Args { p.push(path); // If path is absolute, it replaces the current path. std::fs::canonicalize(p) }) - .map_err(|err| anyhow!("Failed to access path `{}`: {}", path.display(), err,)) + .with_context(|| format!("Failed to access path `{}`", path.display())) } fn parse_assets_path>(path: P) -> Result { diff --git a/src/main.rs b/src/main.rs index 531d0d8..4487524 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,7 +18,7 @@ use crate::server::{Request, Server}; #[cfg(feature = "tls")] use crate::tls::{TlsAcceptor, TlsStream}; -use anyhow::{anyhow, Result}; +use anyhow::{anyhow, Context, Result}; use std::net::{IpAddr, SocketAddr, TcpListener as StdTcpListener}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -35,14 +35,7 @@ use hyper::service::{make_service_fn, service_fn}; use rustls::ServerConfig; #[tokio::main] -async fn main() { - run().await.unwrap_or_else(|err| { - eprintln!("error: {err}"); - std::process::exit(1); - }) -} - -async fn run() -> Result<()> { +async fn main() -> Result<()> { logger::init().map_err(|e| anyhow!("Failed to init logger, {e}"))?; let cmd = build_cli(); let matches = cmd.get_matches(); @@ -94,7 +87,7 @@ fn serve( match bind_addr { BindAddr::Address(ip) => { let incoming = create_addr_incoming(SocketAddr::new(*ip, port)) - .map_err(|e| anyhow!("Failed to bind `{ip}:{port}`, {e}"))?; + .with_context(|| format!("Failed to bind `{ip}:{port}`"))?; match args.tls.as_ref() { #[cfg(feature = "tls")] Some((certs, key)) => { @@ -134,7 +127,7 @@ fn serve( #[cfg(unix)] { let listener = tokio::net::UnixListener::bind(path) - .map_err(|e| anyhow!("Failed to bind `{}`, {e}", path.display()))?; + .with_context(|| format!("Failed to bind `{}`", path.display()))?; let acceptor = unix::UnixAcceptor::from_listener(listener); let new_service = make_service_fn(move |_| serve_func(None)); let server = tokio::spawn(hyper::Server::builder(acceptor).serve(new_service)); @@ -181,8 +174,8 @@ fn print_listening(args: Arc) -> Result<()> { } } if ipv4 || ipv6 { - let ifaces = if_addrs::get_if_addrs() - .map_err(|e| anyhow!("Failed to get local interface addresses: {e}"))?; + let ifaces = + if_addrs::get_if_addrs().with_context(|| "Failed to get local interface addresses")?; for iface in ifaces.into_iter() { let local_ip = iface.ip(); if ipv4 && local_ip.is_ipv4() { diff --git a/src/tls.rs b/src/tls.rs index fac543c..d419892 100644 --- a/src/tls.rs +++ b/src/tls.rs @@ -1,4 +1,4 @@ -use anyhow::{anyhow, bail, Result}; +use anyhow::{anyhow, bail, Context as AnyhowContext, Result}; use core::task::{Context, Poll}; use futures::ready; use hyper::server::accept::Accept; @@ -128,12 +128,11 @@ impl Accept for TlsAcceptor { pub fn load_certs>(filename: T) -> Result> { // Open certificate file. let cert_file = fs::File::open(filename.as_ref()) - .map_err(|e| anyhow!("Failed to access `{}`, {e}", filename.as_ref().display()))?; + .with_context(|| format!("Failed to access `{}`", filename.as_ref().display()))?; let mut reader = io::BufReader::new(cert_file); // Load and return certificate. - let certs = - rustls_pemfile::certs(&mut reader).map_err(|_| anyhow!("Failed to load certificate"))?; + let certs = rustls_pemfile::certs(&mut reader).with_context(|| "Failed to load certificate")?; if certs.is_empty() { bail!("No supported certificate in file"); } @@ -143,12 +142,12 @@ pub fn load_certs>(filename: T) -> Result> { // Load private key from file. pub fn load_private_key>(filename: T) -> Result { let key_file = fs::File::open(filename.as_ref()) - .map_err(|e| anyhow!("Failed to access `{}`, {e}", filename.as_ref().display()))?; + .with_context(|| format!("Failed to access `{}`", filename.as_ref().display()))?; let mut reader = io::BufReader::new(key_file); // Load and return a single private key. let keys = rustls_pemfile::read_all(&mut reader) - .map_err(|e| anyhow!("There was a problem with reading private key: {e}"))? + .with_context(|| "There was a problem with reading private key")? .into_iter() .find_map(|item| match item { rustls_pemfile::Item::RSAKey(key) diff --git a/src/utils.rs b/src/utils.rs index b9e11b7..bfede94 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,4 +1,4 @@ -use anyhow::{anyhow, Result}; +use anyhow::{anyhow, Context, Result}; use std::{ borrow::Cow, path::Path, @@ -8,7 +8,7 @@ use std::{ pub fn unix_now() -> Result { SystemTime::now() .duration_since(UNIX_EPOCH) - .map_err(|err| anyhow!("Invalid system time, {err}")) + .with_context(|| "Invalid system time") } pub fn encode_uri(v: &str) -> String { diff --git a/tests/tls.rs b/tests/tls.rs index 53dc60f..64b38fa 100644 --- a/tests/tls.rs +++ b/tests/tls.rs @@ -37,7 +37,7 @@ fn wrong_path_cert() -> Result<(), Error> { .args(["--tls-cert", "wrong", "--tls-key", "tests/data/key.pem"]) .assert() .failure() - .stderr(contains("error: Failed to access `wrong`")); + .stderr(contains("Failed to access `wrong`")); Ok(()) } @@ -49,7 +49,7 @@ fn wrong_path_key() -> Result<(), Error> { .args(["--tls-cert", "tests/data/cert.pem", "--tls-key", "wrong"]) .assert() .failure() - .stderr(contains("error: Failed to access `wrong`")); + .stderr(contains("Failed to access `wrong`")); Ok(()) }