From ac84a6acb5a09d6b500b2c4911d0a258345fdf6f Mon Sep 17 00:00:00 2001 From: Lumither Tao Date: Sat, 4 May 2024 22:55:45 +0800 Subject: [PATCH] feat(backend/api/get/post) fix error handling --- backend/src/api/get/get_post.rs | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/backend/src/api/get/get_post.rs b/backend/src/api/get/get_post.rs index 4ea0991..d80efa9 100644 --- a/backend/src/api/get/get_post.rs +++ b/backend/src/api/get/get_post.rs @@ -1,17 +1,18 @@ use std::str::FromStr; use axum::extract::{Path, State}; +use axum::http::StatusCode; use axum::Json; use chrono::NaiveDateTime; use serde_json::{json, Map, Value}; -use sqlx::{PgPool, query, Row}; +use sqlx::{Error, PgPool, query, Row}; use uuid::Uuid; pub async fn get_post( State(db_connection): State, Path(post_id): Path, -) -> Result, Json> { - let meta = query( +) -> Result, (StatusCode, Json)> { + let meta = match query( r#" SELECT * FROM Post @@ -20,8 +21,30 @@ WHERE post_id = $1; ) .bind(Uuid::from_str(post_id.as_str()).expect("Failed to parse UUID")) .fetch_one(&db_connection) - .await - .expect("Failed to execute db query"); + .await { + Ok(value) => { value } + Err(e) => { + return match e { + Error::RowNotFound => { + Err(( + StatusCode::BAD_REQUEST, + Json::from(json!(format!( + "{{error: {}}}", + e.to_string() + ))))) + } + _ => { + Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json::from(json!(format!( + "{{error: {}}}", + e.to_string() + ))))) + } + }; + } + }; + let tags = query( r#"