improve error handling part 3

main
Mathias Rothenhaeusler 2025-03-07 17:01:02 +01:00
parent 5642ab4717
commit f84387d238
2 changed files with 23 additions and 11 deletions

View File

@ -1,30 +1,43 @@
use core::fmt;
use mysql::{Opts, Pool, PooledConn};
use std::{
env,
error::Error,
path::PathBuf,
sync::{Arc, Mutex},
};
use directories::BaseDirs;
#[derive(Debug)]
struct InitError(String);
impl fmt::Display for InitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Error for InitError {}
#[derive(Debug)]
pub struct Db {
pool: Arc<Mutex<Pool>>,
}
impl Db {
pub fn initialize(env: String) -> Result<Self, mysql::Error> {
let base_dir: BaseDirs = match BaseDirs::new() {
Some(dirs) => dirs,
None => panic!("No config folder found."),
};
pub fn initialize(env: String) -> Result<Self, Box<dyn std::error::Error>> {
let base_dir: BaseDirs = BaseDirs::new()
.ok_or_else(|| Box::new(InitError("No config folder found.".to_string())))?;
let config_file_path: PathBuf = base_dir.config_dir().join("rcc/").join(env);
match dotenv::from_path(config_file_path.as_path()) {
Ok(env) => env,
Err(_) => panic!("Could not load .env file {:?}", config_file_path.as_path()),
};
dotenv::from_path(config_file_path.as_path()).map_err(|_| {
Box::new(InitError(format!(
"Failed to load dotenv file '{}'",
config_file_path.display()
)))
})?;
let location: String = env::var("LOCATION").unwrap_or_else(|_| "localhost".to_string());
let user: String = env::var("USERNAME").unwrap();

View File

@ -15,8 +15,7 @@ impl FileRepo {
pub fn find_page(&mut self, file_id: &usize) -> Result<Vec<Page>, mysql::Error> {
let mut connection: mysql::PooledConn = self.db_pool.get_connection()?;
let stat = connection
.prep("SELECT m_id, description, file FROM global_data.effi_file_mapping WHERE file_id = :file_id")
.unwrap();
.prep("SELECT m_id, description, file FROM global_data.effi_file_mapping WHERE file_id = :file_id")?;
connection.exec_map(
stat,