client: Handle unexpected responses as errors

This commit is contained in:
Elias Projahn 2021-04-15 17:00:37 +02:00
parent bb33b30f6e
commit f4254cc431

View file

@ -109,38 +109,38 @@ impl Client {
.body(())? .body(())?
.send_async() .send_async()
.await?; .await?;
let body = response.text().await?; match response.status() {
StatusCode::OK => Ok(response.text().await?),
Ok(body) status_code => Err(Error::UnexpectedResponse(status_code)),
}
} }
/// Make an authenticated post request to the server. /// Make an authenticated post request to the server.
async fn post(&self, url: &str, body: String) -> Result<String> { async fn post(&self, url: &str, body: String) -> Result<String> {
let body = if self.token.borrow().is_some() { // Try to do the request using a cached login token.
if self.token.borrow().is_some() {
let mut response = self.post_priv(url, body.clone()).await?; let mut response = self.post_priv(url, body.clone()).await?;
// Try one more time (maybe the token was expired) // If authorization failed, try again below. Else, return early.
if response.status() == StatusCode::UNAUTHORIZED { match response.status() {
if self.login().await? { StatusCode::UNAUTHORIZED => (),
response = self.post_priv(url, body).await?; StatusCode::OK => return Ok(response.text().await?),
} else { status_code => return Err(Error::UnexpectedResponse(status_code)),
Err(Error::LoginFailed)?;
}
} }
}
response.text().await? if self.login().await? {
let mut response = self.post_priv(url, body).await?;
match response.status() {
StatusCode::OK => Ok(response.text().await?),
StatusCode::UNAUTHORIZED => Err(Error::Unauthorized),
status_code => Err(Error::UnexpectedResponse(status_code)),
}
} else { } else {
let mut response = if self.login().await? { Err(Error::LoginFailed)
self.post_priv(url, body).await? }
} else {
Err(Error::LoginFailed)?
};
response.text().await?
};
Ok(body)
} }
/// Post something to the server assuming there is a valid login token. /// Post something to the server assuming there is a valid login token.