feat: improve error handling and messages

This commit is contained in:
Alexander Navarro 2025-01-21 13:29:01 -03:00
parent e65afb8553
commit 5d1b4bdfd8
3 changed files with 26 additions and 6 deletions

View file

@ -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(())

View file

@ -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),
}

View file

@ -5,6 +5,7 @@ use sqlx::Row as _;
use sqlx::TypeInfo;
use crate::error;
use crate::error::Error;
#[derive(Debug)]
pub struct Column<T> {
@ -28,7 +29,10 @@ pub enum ColumnType {
impl ColumnType {
pub fn new(row: &PgRow, idx: usize) -> error::Result<Self> {
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))),
}
}
}