From e65afb855332ec0ff71187ca6972d31e5a1d64d9 Mon Sep 17 00:00:00 2001 From: aleidk Date: Tue, 21 Jan 2025 11:43:59 -0300 Subject: [PATCH] feat: add thiserror for error handling --- Cargo.lock | 1 + Cargo.toml | 3 ++- src/bin/cli/main.rs | 13 ++++++++----- src/error.rs | 17 ++++++++++++++++- 4 files changed, 27 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 62abe0b..443a9cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1391,6 +1391,7 @@ dependencies = [ "clap", "futures", "sqlx", + "thiserror", "tokio", ] diff --git a/Cargo.toml b/Cargo.toml index 3602b7e..9dd378a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,4 +14,5 @@ sqlx = { version = "0.8", features = [ "sqlite", "chrono", ] } -tokio = {version = "1.43.0", features = ["full"]} +thiserror = "2.0.11" +tokio = { version = "1.43.0", features = ["full"] } diff --git a/src/bin/cli/main.rs b/src/bin/cli/main.rs index cdc5ff5..5debcd5 100644 --- a/src/bin/cli/main.rs +++ b/src/bin/cli/main.rs @@ -2,6 +2,7 @@ use clap::{Parser, Subcommand}; use futures::TryStreamExt; +use simple_crud::error::Result; use simple_crud::sql::ColumnType; use sqlx::postgres::PgPool; use sqlx::Column; @@ -21,7 +22,7 @@ struct Cli { #[derive(Subcommand)] enum Commands { - /// Executes a query agains the database, it pass it directly to the underliying driver + /// Executes a query against the database, it pass it directly to the underlying driver Query { /// Query to execute sql: String, @@ -29,7 +30,7 @@ enum Commands { } #[tokio::main] -async fn main() { +async fn main() -> Result<()> { let cli = Cli::parse(); let url = cli.db_url.unwrap(); @@ -37,18 +38,20 @@ async fn main() { // You can check for the existence of subcommands, and if found use their // matches just as you would the top level cmd match &cli.command { - Commands::Query { sql } => handle_query(url, sql).await.unwrap(), + Commands::Query { sql } => handle_query(url, sql).await?, } + + Ok(()) } -async fn handle_query(url: String, query: &String) -> Result<(), sqlx::Error> { +async fn handle_query(url: String, query: &String) -> Result<()> { let pool = PgPool::connect(url.as_str()).await?; let mut rows = sqlx::query(query.as_str()).fetch(&pool); while let Some(row) = rows.try_next().await? { for idx in 0..row.len() { - let column = ColumnType::new(&row, idx).unwrap(); + let column = ColumnType::new(&row, idx)?; // let value = String::from(row.get(col.ordinal())); println!("Column {:?}", column); } diff --git a/src/error.rs b/src/error.rs index 708451d..fdcefc5 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1 +1,16 @@ -pub type Result = std::result::Result>; +pub type Result = std::result::Result; + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error("Unhandled error: {0}")] + Generic(String), + + #[error("Unhandled error: {0}")] + Static(&'static str), + + #[error(transparent)] + IO(#[from] std::io::Error), + + #[error("Error performing database operation.")] + DatabaseOperation(#[from] sqlx::Error), +}