Improve error handling

This commit is contained in:
Xiretza 2024-02-15 20:14:07 +00:00
parent fa7dc5a3f9
commit 360f3fcbbf
2 changed files with 28 additions and 19 deletions

View file

@ -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<Self, sqlx::Error> {
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(())
}
}

View file

@ -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<Mutex<Box<dyn Database + Send>>> = 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));