1
0
Fork 0

simpler error handling

This commit is contained in:
Cyborus 2024-01-18 14:48:31 -05:00
parent 81b17abc8a
commit 6ee958ce86
No known key found for this signature in database

View file

@ -26,8 +26,8 @@ pub enum ForgejoError {
BadStructure(#[source] serde_json::Error, String), BadStructure(#[source] serde_json::Error, String),
#[error("unexpected status code {} {}", .0.as_u16(), .0.canonical_reason().unwrap_or(""))] #[error("unexpected status code {} {}", .0.as_u16(), .0.canonical_reason().unwrap_or(""))]
UnexpectedStatusCode(StatusCode), UnexpectedStatusCode(StatusCode),
#[error("{} {}: {}", .0.as_u16(), .0.canonical_reason().unwrap_or(""), .1)] #[error("{} {}{}", .0.as_u16(), .0.canonical_reason().unwrap_or(""), .1.as_ref().map(|s| format!(": {s}")).unwrap_or_default())]
ApiError(StatusCode, String), ApiError(StatusCode, Option<String>),
#[error("the provided authorization was too long to accept")] #[error("the provided authorization was too long to accept")]
AuthTooLong, AuthTooLong,
} }
@ -148,22 +148,21 @@ impl Forgejo {
let response = self.client.execute(request).await?; let response = self.client.execute(request).await?;
match response.status() { match response.status() {
status if status.is_success() => Ok(response), status if status.is_success() => Ok(response),
status if status.is_client_error() => Err(ForgejoError::ApiError( status if status.is_client_error() => {
status, Err(ForgejoError::ApiError(status, maybe_err(response).await))
response }
.json::<ErrorMessage>()
.await?
.message
.unwrap_or_else(|| String::from("[no message]")),
)),
status => Err(ForgejoError::UnexpectedStatusCode(status)), status => Err(ForgejoError::UnexpectedStatusCode(status)),
} }
} }
} }
async fn maybe_err(res: reqwest::Response) -> Option<String> {
res.json::<ErrorMessage>().await.ok().map(|e| e.message)
}
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
struct ErrorMessage { struct ErrorMessage {
message: Option<String>, message: String,
// intentionally ignored, no need for now // intentionally ignored, no need for now
// url: Url // url: Url
} }