我目前正在通过将 Swagger 文档 HTTP 错误响应添加到每个 URI 函数来生成它们,如下所示:
#[utoipa::path(
context_path = "/user",
tag = "user",
responses(
(status = 200, description = "Endpoint to get all data from a user.",
body = Value,
example = json!({
"id": 12,
"user_id": "TestUser42",
"class": "8a",
"created_at": "07-04-2004",
"user_data": {
"traffic": [],
"modules": []
}
})
),
(status = 401, description = "Access token is missing or invalid",
body = HttpError,
example = json!({
"time": "07-05-2024 08:17:33",
"status_code": "401",
"error_type": "Unauthorized",
"reason": "Access token is missing or invalid"
})
),
(status = 404, description = "ID not found", body = HttpError,
example = json!({
"time": "07-05-2024 08:17:33",
"status_code": "404",
"error_type": "NotFound",
"reason": "ID not found"
})
),
(status = 403, description = "Not allowed to call this endpoint with the current permission", body = HttpError,
example = json!({
"time": "07-05-2024 08:17:33",
"status_code": "403",
"error_type": "AccessForbidden",
"reason": "Wrong or missing permissions"
})
)
),
security(
("bearerAuth" = [])
)
)]
#[get("/get")]
#[protect(any("STUDENT", "ADMIN", "TEACHER", "MAKERSPACE"), error = "access_denied")]
pub async fn get_user(
claims: Option<web::ReqData<Claims>>
) -> impl Responder {
if let Some(claims) = claims {
match user_service::get_user(claims.sub.as_str()).await {
Ok(u) => HttpResponse::Ok().json(u),
Err(_) => HttpError::not_found("User does not exist").error_response()
}
} else {
HttpError::bad_gateway("Unable to get user").error_response()
}
}
如何通过将 HTTP 错误元组放入 JSON 文件或不同的 Rust 文件来重构它?
因为
401, 403, and 404
始终是相同的代码片段。
在 Rust 论坛的一些帮助下,我找到了解决方案!
IntoResponses
,就像 @kmdreko 之前提到的那样,我不知道我可以使用 ContentBuilder
,它允许我创建一个示例,然后使用 Content
返回
build()
。
如果您也想实施,可以在这里找到我的解决方案。
impl IntoResponses for HttpError {
fn responses() -> BTreeMap<String, RefOr<Response>> {
ResponsesBuilder::new()
.response("401", ResponseBuilder::new()
.description("JWT invalid or missing")
.content(
"application/json",
ContentBuilder::new()
.example(Some(json!({
"time": "07-05-2024 08:17:33".to_string(),
"status_code": "401".to_string(),
"error_type": ErrorResponse::Unauthorized,
"reason": Some("JWT missing or invalid".to_string()),
}))
).build()
)
)
.response("403", ResponseBuilder::new()
.description("Not allowed to call this endpoint with the current permission")
.content(
"application/json",
ContentBuilder::new()
.example(Some(json!( {
"time": "07-05-2024 08:17:33".to_string(),
"status_code": "403".to_string(),
"error_type": ErrorResponse::Forbidden,
"reason": Some("Access Forbidden".to_string()),
}))
).build()
)
)
.build()
.into()
}
}
HttpError
是我处理 HTTP 错误响应的结构。