]> OzVa Git service - ozva-cloud/commitdiff
refactor: improve error handle (#195)
authorsigoden <sigoden@gmail.com>
Sun, 12 Mar 2023 07:20:40 +0000 (15:20 +0800)
committerGitHub <noreply@github.com>
Sun, 12 Mar 2023 07:20:40 +0000 (15:20 +0800)
src/args.rs
src/main.rs
src/tls.rs
src/utils.rs
tests/tls.rs

index 44ab591d466a31d9b5d1af1b2037bedfb971eea1..48c9afae210e62530d2030a398a3e6751d7cef36 100644 (file)
@@ -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<P: AsRef<Path>>(path: P) -> Result<PathBuf> {
index 531d0d8e2862ab3cb580e5ca06e8a39147f19203..4487524a3ecf07ca9a46f62209289956cb555b8f 100644 (file)
@@ -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<Args>) -> 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() {
index fac543ce8fa93940e3ae292df5de7681d657dbc2..d419892ea7c7a138ffec81c5b2d69ab152b3f2ff 100644 (file)
@@ -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<T: AsRef<Path>>(filename: T) -> Result<Vec<Certificate>> {
     // 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<T: AsRef<Path>>(filename: T) -> Result<Vec<Certificate>> {
 // Load private key from file.
 pub fn load_private_key<T: AsRef<Path>>(filename: T) -> Result<PrivateKey> {
     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)
index b9e11b73aba1a1e1e33e8fea876f673ffe7f81d9..bfede94f6c624237e4f7a0f4e7665fb9205f2ae3 100644 (file)
@@ -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<Duration> {
     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 {
index 53dc60f3ea7f3807d657e11af9ad2c22a76e3515..64b38fa04a47b5522a34c6fdfb04b6c4dc5440fd 100644 (file)
@@ -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(())
 }