feat(backend/api/get/post) fix error handling

This commit is contained in:
lumither committed 2024-05-04 22:55:45 +08:00
1 parent a4d0b7140a
commit ac84a6acb5
1 file changed
+28 -5
+28 -5
View File
@@ -1,17 +1,18 @@
use std::str::FromStr; use std::str::FromStr;
use axum::extract::{Path, State}; use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::Json; use axum::Json;
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use serde_json::{json, Map, Value}; use serde_json::{json, Map, Value};
use sqlx::{PgPool, query, Row}; use sqlx::{Error, PgPool, query, Row};
use uuid::Uuid; use uuid::Uuid;
pub async fn get_post( pub async fn get_post(
State(db_connection): State<PgPool>, State(db_connection): State<PgPool>,
Path(post_id): Path<String>, Path(post_id): Path<String>,
) -> Result<Json<Value>, Json<Value>> { ) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let meta = query( let meta = match query(
r#" r#"
SELECT * SELECT *
FROM Post FROM Post
@@ -20,8 +21,30 @@ WHERE post_id = $1;
) )
.bind(Uuid::from_str(post_id.as_str()).expect("Failed to parse UUID")) .bind(Uuid::from_str(post_id.as_str()).expect("Failed to parse UUID"))
.fetch_one(&db_connection) .fetch_one(&db_connection)
.await .await {
.expect("Failed to execute db query"); 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( let tags = query(
r#" r#"