From c23fcdc9bdc08d1609619d9de3c3f68d6bac82fd Mon Sep 17 00:00:00 2001 From: SinTan1729 Date: Mon, 21 Apr 2025 22:20:11 -0500 Subject: [PATCH] chg: Properly validate error types --- actix/src/database.rs | 5 ++--- actix/src/utils.rs | 14 ++++++++++---- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/actix/src/database.rs b/actix/src/database.rs index c86142f..52d121b 100644 --- a/actix/src/database.rs +++ b/actix/src/database.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2023 Sayantan Santra // SPDX-License-Identifier: MIT -use rusqlite::Connection; +use rusqlite::{Connection, Error}; use serde::Serialize; // Struct for encoding a DB row @@ -67,12 +67,11 @@ pub fn add_hit(shortlink: &str, db: &Connection) { } // Insert a new link -pub fn add_link(shortlink: String, longlink: String, db: &Connection) -> bool { +pub fn add_link(shortlink: String, longlink: String, db: &Connection) -> Result { db.execute( "INSERT INTO urls (long_url, short_url, hits) VALUES (?1, ?2, ?3)", (longlink, shortlink, 0), ) - .is_ok() } // Delete and existing link diff --git a/actix/src/utils.rs b/actix/src/utils.rs index f3c4618..e82d575 100644 --- a/actix/src/utils.rs +++ b/actix/src/utils.rs @@ -128,10 +128,16 @@ pub fn add_link(req: String, db: &Connection) -> (bool, String) { } if validate_link(chunks.shortlink.as_str()) { - if database::add_link(chunks.shortlink.clone(), chunks.longlink, db) { - (true, chunks.shortlink) - } else { - (false, String::from("Short URL is already in use!")) + match database::add_link(chunks.shortlink.clone(), chunks.longlink, db) { + Ok(_) => (true, chunks.shortlink), + Err(error) => { + if error.to_string() == "UNIQUE constraint failed: urls.short_url" { + (false, String::from("Short URL is already in use!")) + } else { + // This should be super rare + (false, String::from("Something went wrong!")) + } + } } } else { (false, String::from("Short URL is not valid!"))