【发布时间】:2021-06-05 21:29:52
【问题描述】:
我尝试在 Rust 的 Rocket 中返回带有错误的 json 正文。
pub fn error_status(error: Error) -> Status {
match error {
Error::NotFound => Status::NotFound,
_ => Status::InternalServerError
}
}
#[get("/user/<id>")]
pub fn get_user(id: i32, connection: DbConn) -> Result<Json<User>, Status> {
UserService::show_user(id, &connection)
.map(|u| Json(u))
.map_err(|err| core::error_status(err))
}
当发生错误时,它返回Status::NotFound,但使用 html 正文,我需要 json 正文。
我尝试使用Return JSON with an HTTP status other than 200 in Rocket
,但没有成功。在该主题中,作者使用JsonValue 我需要Json(T) 作为动态json 正文。我无法成功创建响应:/
我可以使用errorCatcher,但我不想在所有响应中都使用它,我只在api响应中需要json。
如何使用 json 正文返回错误? 提前谢谢你。
【问题讨论】:
标签: rust response jsonresponse rust-rocket