From 360f3fcbbfa1707603e83e0462978e90a49d6b52 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Thu, 15 Feb 2024 20:14:07 +0000 Subject: [PATCH] Improve error handling --- src/db.rs | 21 +++++++++------------ src/main.rs | 26 +++++++++++++++++++------- 2 files changed, 28 insertions(+), 19 deletions(-) diff --git a/src/db.rs b/src/db.rs index 66c97ab..a146b4e 100644 --- a/src/db.rs +++ b/src/db.rs @@ -43,24 +43,20 @@ pub struct SqliteDatabase { impl SqliteDatabase { #[instrument] - pub async fn open(connection_string: &str) -> Self { - let options = SqliteConnectOptions::from_str(connection_string) - .expect("Invalid database URI") - .create_if_missing(true); + pub async fn open(connection_string: &str) -> Result { + let options = SqliteConnectOptions::from_str(connection_string)?.create_if_missing(true); let mut db = Self { - conn: SqliteConnection::connect_with(&options) - .await - .expect("Failed to open SQLite database"), + conn: SqliteConnection::connect_with(&options).await?, }; - db.init().await; + db.init().await?; - db + Ok(db) } #[instrument] - pub async fn init(&mut self) { + async fn init(&mut self) -> Result<(), sqlx::Error> { query!( "CREATE TABLE IF NOT EXISTS user_tokens ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -72,8 +68,9 @@ impl SqliteDatabase { )" ) .execute(&mut self.conn) - .await - .expect("Failed to initialize table user_tokens"); + .await?; + + Ok(()) } } diff --git a/src/main.rs b/src/main.rs index 73c54d0..b3f6115 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,13 +25,13 @@ mod db; mod secrets; mod server; -use std::sync::Arc; +use std::{path::PathBuf, sync::Arc}; use auth::{ AuthenticationBackend, ServerPadlockGenerator, UserAuthenticator, UserServerKeyGenerator, }; use clap::Parser; -use color_eyre::Result; +use color_eyre::{eyre::Context, Result}; use config::Config; use db::{Database, SqliteDatabase}; use tokio::sync::Mutex; @@ -78,17 +78,29 @@ struct Args { async fn main() -> Result<()> { let args = Args::parse(); - init()?; + init().context("Failed to initialize tracing")?; - let config = load_config(&args.config).await?; + let config = load_config(&args.config).await.with_context(|| { + if let Ok(path) = PathBuf::from(&args.config).canonicalize() { + format!("Failed to load config from {path:?}") + } else { + format!("Failed to load config from invalid path {}", &args.config) + } + })?; let database: Arc>> = Arc::new(Mutex::new(Box::new( - SqliteDatabase::open(&config.database.connection_string).await, + SqliteDatabase::open(&config.database.connection_string) + .await + .context("Failed to open database")?, ))); let mut auth_backends = vec![]; - for c in config.auth_backends { - auth_backends.push(AuthenticationBackend::new(c).await?); + for (i, c) in config.auth_backends.into_iter().enumerate() { + auth_backends.push( + AuthenticationBackend::new(c) + .await + .with_context(|| format!("Failed to initialize backend {i}"))?, + ); } let user_authenticator = Arc::new(UserAuthenticator::new(database, auth_backends));