From 0dd505cf1231880d82c87ccf9ead8fce2cf01e50 Mon Sep 17 00:00:00 2001 From: ZTL-UwU Date: Sun, 24 Dec 2023 11:23:19 +0800 Subject: [PATCH] feat: add error catchers Signed-off-by: ZTL-UwU --- README.md | 2 -- api/src/lib.rs | 44 +++++++++++++++++++++++++++++++++----------- entity/src/req.rs | 3 +-- 3 files changed, 34 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index f103c3b..f212849 100644 --- a/README.md +++ b/README.md @@ -50,14 +50,12 @@ cargo run | 名称 | 类型 | 内容 | | :----------- | :----- | :--------------------------------------------------------------------- | -| `code` | i32 | 响应代码 | | `msg` | String | 返回信息 | | `similarity` | [] | 表示前 5 个相似度最高的论文,每项第一个值表示相似度,第二个值为论文 id | ```json { - "code": 200, "msg": "加入成功", "similarity": [ [ diff --git a/api/src/lib.rs b/api/src/lib.rs index e160d7c..f6b1d11 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -1,6 +1,7 @@ extern crate rocket; use rocket::fairing::{self, AdHoc}; +use rocket::http::Status; use rocket::serde::json::Json; use rocket::{Build, Rocket}; @@ -22,24 +23,44 @@ async fn check( data: Json, state: &rocket::State, conn: Connection<'_, Db>, -) -> Json { +) -> (Status, Json) { let req: ReqData = data.into_inner(); let db = conn.into_inner(); match process::similarity(&req, req.write, db, &state.jieba, &state.stop_words).await { - Ok(r) => Json(ResData { - code: 200, - msg: format!("{}成功", if req.write { "加入" } else { "查询" }), - similarity: r, - }), - Err(e) => Json(ResData { - code: 500, - msg: e.to_string(), - similarity: [].to_vec(), - }), + Ok(r) => ( + Status::Ok, + Json(ResData { + msg: format!("{}成功", if req.write { "加入" } else { "查询" }), + similarity: Some(r), + }), + ), + Err(e) => ( + Status::InternalServerError, + Json(ResData { + msg: e.to_string(), + similarity: None, + }), + ), } } +#[rocket::catch(404)] +fn not_found(req: &rocket::Request) -> Json { + Json(ResData { + msg: format!("'{}'不存在", req.uri()), + similarity: None, + }) +} + +#[rocket::catch(400)] +fn bad_req() -> Json { + Json(ResData { + msg: "调用有误".to_string(), + similarity: None, + }) +} + async fn run_migrations(rocket: Rocket) -> fairing::Result { let conn = &Db::fetch(&rocket).unwrap().conn; let _ = migration::Migrator::up(conn, None).await; @@ -52,6 +73,7 @@ async fn start() -> Result<(), rocket::Error> { .attach(Db::init()) .attach(AdHoc::try_on_ignite("Migrations", run_migrations)) .mount("/", rocket::routes![check]) + .register("/", rocket::catchers![not_found, bad_req]) .manage(SharedData { jieba: jieba_rs::Jieba::new(), stop_words: data::stop_words(), diff --git a/entity/src/req.rs b/entity/src/req.rs index f15333e..58e8cae 100644 --- a/entity/src/req.rs +++ b/entity/src/req.rs @@ -8,9 +8,8 @@ pub struct ReqData { #[derive(Serialize, Debug)] pub struct ResData { - pub code: i16, pub msg: String, - pub similarity: Vec<(f64, String)>, + pub similarity: Option>, } /// Data shared through services as a Rocket state.