From 8d1fe3b8f2dd2c302af6333bc2e6a699a8a09280 Mon Sep 17 00:00:00 2001 From: Mariano Riefolo Date: Mon, 2 Sep 2024 11:52:13 +0200 Subject: [PATCH] feat(api): improve error handling --- src/api/mod.rs | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/src/api/mod.rs b/src/api/mod.rs index f72d633..b016ecc 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -51,6 +51,9 @@ pub async fn pdf() -> impl IntoResponse { async fn download_pdf(id: u8) -> Result { let links = get_pdf_links().await.unwrap(); + if id as usize >= links.len() { + return Err(failure::err_msg("Invalid ID")); + } let url = &links[id as usize]; let mut hasher = Sha1::new(); @@ -92,7 +95,15 @@ pub struct Header { } pub async fn get_classes(Query(params): Query) -> impl IntoResponse { - let filename = download_pdf(params.id).await.unwrap(); + let filename = match download_pdf(params.id).await { + Ok(x) => x, + Err(_) => { + return ( + StatusCode::UNPROCESSABLE_ENTITY, + Json(json!({ "errore": "ID non valido"})), + ) + } + }; let csv_content = fs::read_to_string(&filename).unwrap(); let mut rdr = csv::Reader::from_reader(csv_content.as_bytes()); @@ -126,7 +137,15 @@ pub struct FilterByClassQuery { } pub async fn get_teachers(Query(params): Query) -> impl IntoResponse { - let filename = download_pdf(params.id).await.unwrap(); + let filename = match download_pdf(params.id).await { + Ok(x) => x, + Err(_) => { + return ( + StatusCode::UNPROCESSABLE_ENTITY, + Json(json!({ "errore": "ID non valido"})), + ) + } + }; let csv_content = fs::read_to_string(&filename).unwrap(); let mut rdr = csv::Reader::from_reader(csv_content.as_bytes()); @@ -135,7 +154,15 @@ pub async fn get_teachers(Query(params): Query) -> impl Into let mut result: HashMap> = HashMap::new(); for record in rdr.records() { - let record = record.unwrap(); + let record = match record { + Ok(x) => x, + Err(_) => { + return ( + StatusCode::UNPROCESSABLE_ENTITY, + Json(json!({ "errore": "Formato non supportato"})), + ) + } + }; for (i, cell) in record.iter().enumerate() { if cell == params.classe { for (day, range) in header.weekdays.clone() {