Rocket rust 不可处理实体返回json错误

x33g5p2x  于 2022-11-26  发布在  其他
关注(0)|答案(1)|浏览(202)

我正在使用Rocket制作一个API,我在这个API中还只是个新手。
我正在阅读文档,但是当收到的json不正确时,我找不到返回json错误的方法。
这是我的结构

#[derive(Deserialize, Serialize, Clone, Validate)]
#[serde(crate = "rocket::serde", rename_all = "camelCase")]
pub struct Point {
    #[validate(length(min = 10))]
    pub picture: String,
    pub geo_location: GeoLocation,
    pub description: String,
    pub address: String,
    pub place_name: String,
    pub user: String,
}

# My handle controller
#[post("/point", format = "application/json", data = "<data>")]
pub fn new_point(
    data: Validated<Json<Point>>,
) -> Result<status::Custom<Json<Point>>, status::Custom<Json<ErrorType>>> {
    let point: Point = data.into_inner().into_inner();
    // .........
}

而且这是可行的,但是如果我发送了一些错误的json,我只是收到一个html页面。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>422 Unprocessable Entity</title>
</head>

<body align="center">
    <div role="main" align="center">
        <h1>422: Unprocessable Entity</h1>
        <p>The request was well-formed but was unable to be followed due to semantic errors.</p>
<!-- ...... -->

日志中显示错误:

Data guard `Validated < Json < Point > >` failed: Err(Parse("{\r\n    \"picture\": \"fdddddddddddd\",\r\n    \"eoLocation\": {\r\n        \"latitude\": 0.1,\r\n        \"longitud
e\": 0.1\r\n    },\r\n    \"description\": \"Works\",\r\n    \"address\": \"Full address\",\r\n    \"user\": \"Fulano\",\r\n    \"placeName\": \"....\"\r\n}", Error("missing field `geoLocation`", line: 11, column: 1))).

我怎么能做这样的回报:

{
  "error": {
    "message": "missing field `geoLocation`"
  }
}

我用尽全力接住:

#[catch(422)]
fn unprocessable_entity(req: &Request) -> String {
    format!("message: Some error happen")
}

但是我无法在示例Request中获得错误消息。
我怎样做才能得到解析错误并在我的主体api中返回?
谢谢你

7gs2gvoe

7gs2gvoe1#

您可以尝试以下操作:

#[catch(422)]
fn unprocessable_entity(req: &Request) -> String {
    let validation_errors = req.local_cache(|| CachedValidationErrors(None)).0.as_ref();

    let mut message = "Something goes wrong!".to_string();
 
    if validation_errors.is_some() {
        message.clear();
        
        let erros = validation_errors.unwrap().field_errors();
        
        for (_,val) in erros.iter() {
            for error in val.iter() {
                message.push_str(error.message.as_ref().unwrap());
            }
        }
    }
    ApiError { code: StatusCode::BadRequest, message: message }

}

相关问题