From 5d1b4bdfd86692910792d6c2063889c921cc0a31 Mon Sep 17 00:00:00 2001 From: aleidk Date: Tue, 21 Jan 2025 13:29:01 -0300 Subject: [PATCH] feat: improve error handling and messages --- src/bin/cli/main.rs | 16 +++++++++++++--- src/error.rs | 8 +++++++- src/sql.rs | 8 ++++++-- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/bin/cli/main.rs b/src/bin/cli/main.rs index 5debcd5..db45bf7 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::Error; use simple_crud::error::Result; use simple_crud::sql::ColumnType; use sqlx::postgres::PgPool; @@ -33,12 +34,21 @@ enum Commands { async fn main() -> Result<()> { let cli = Cli::parse(); - let url = cli.db_url.unwrap(); + let url = match cli.db_url { + Some(url) => url, + None => { + panic!("{}", Error::Runtime("No db_url provided.")); + } + }; // 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?, + let result = match &cli.command { + Commands::Query { sql } => handle_query(url, sql).await, + }; + + if let Err(err) = result { + panic!("{}", err); } Ok(()) diff --git a/src/error.rs b/src/error.rs index fdcefc5..5f2ad4f 100644 --- a/src/error.rs +++ b/src/error.rs @@ -11,6 +11,12 @@ pub enum Error { #[error(transparent)] IO(#[from] std::io::Error), - #[error("Error performing database operation.")] + #[error("Error in runtime execution: {0}")] + Runtime(&'static str), + + #[error("Error parsing database column type: {0}")] + ColumnParse(String), + + #[error(transparent)] DatabaseOperation(#[from] sqlx::Error), } diff --git a/src/sql.rs b/src/sql.rs index aad91ec..cfa208e 100644 --- a/src/sql.rs +++ b/src/sql.rs @@ -5,6 +5,7 @@ use sqlx::Row as _; use sqlx::TypeInfo; use crate::error; +use crate::error::Error; #[derive(Debug)] pub struct Column { @@ -28,7 +29,10 @@ pub enum ColumnType { impl ColumnType { pub fn new(row: &PgRow, idx: usize) -> error::Result { - let column = row.columns().get(idx).unwrap(); + let column = row + .columns() + .get(idx) + .ok_or_else(|| Error::ColumnParse(String::from("Could not get column")))?; let sql_type = column.type_info().name(); let name = String::from(column.name()); @@ -106,7 +110,7 @@ impl ColumnType { name, })) } - &_ => panic!("{} Type not found!", sql_type), + &_ => Err(Error::ColumnParse(format!("{} type not found!", sql_type))), } } }