Use anyhow
more idiomatically (#31052)
https://github.com/zed-industries/zed/issues/30972 brought up another case where our context is not enough to track the actual source of the issue: we get a general top-level error without inner error. The reason for this was `.ok_or_else(|| anyhow!("failed to read HEAD SHA"))?; ` on the top level. The PR finally reworks the way we use anyhow to reduce such issues (or at least make it simpler to bubble them up later in a fix). On top of that, uses a few more anyhow methods for better readability. * `.ok_or_else(|| anyhow!("..."))`, `map_err` and other similar error conversion/option reporting cases are replaced with `context` and `with_context` calls * in addition to that, various `anyhow!("failed to do ...")` are stripped with `.context("Doing ...")` messages instead to remove the parasitic `failed to` text * `anyhow::ensure!` is used instead of `if ... { return Err(...); }` calls * `anyhow::bail!` is used instead of `return Err(anyhow!(...));` Release Notes: - N/A
This commit is contained in:
parent
1e51a7ac44
commit
16366cf9f2
294 changed files with 2037 additions and 2610 deletions
|
@ -133,21 +133,20 @@ enum CopilotServer {
|
|||
impl CopilotServer {
|
||||
fn as_authenticated(&mut self) -> Result<&mut RunningCopilotServer> {
|
||||
let server = self.as_running()?;
|
||||
if matches!(server.sign_in_status, SignInStatus::Authorized { .. }) {
|
||||
Ok(server)
|
||||
} else {
|
||||
Err(anyhow!("must sign in before using copilot"))
|
||||
}
|
||||
anyhow::ensure!(
|
||||
matches!(server.sign_in_status, SignInStatus::Authorized { .. }),
|
||||
"must sign in before using copilot"
|
||||
);
|
||||
Ok(server)
|
||||
}
|
||||
|
||||
fn as_running(&mut self) -> Result<&mut RunningCopilotServer> {
|
||||
match self {
|
||||
CopilotServer::Starting { .. } => Err(anyhow!("copilot is still starting")),
|
||||
CopilotServer::Disabled => Err(anyhow!("copilot is disabled")),
|
||||
CopilotServer::Error(error) => Err(anyhow!(
|
||||
"copilot was not started because of an error: {}",
|
||||
error
|
||||
)),
|
||||
CopilotServer::Starting { .. } => anyhow::bail!("copilot is still starting"),
|
||||
CopilotServer::Disabled => anyhow::bail!("copilot is disabled"),
|
||||
CopilotServer::Error(error) => {
|
||||
anyhow::bail!("copilot was not started because of an error: {error}")
|
||||
}
|
||||
CopilotServer::Running(server) => Ok(server),
|
||||
}
|
||||
}
|
||||
|
@ -648,7 +647,7 @@ impl Copilot {
|
|||
}
|
||||
};
|
||||
|
||||
cx.background_spawn(task.map_err(|err| anyhow!("{:?}", err)))
|
||||
cx.background_spawn(task.map_err(|err| anyhow!("{err:?}")))
|
||||
} else {
|
||||
// If we're downloading, wait until download is finished
|
||||
// If we're in a stuck state, display to the user
|
||||
|
|
|
@ -2,6 +2,7 @@ use std::path::PathBuf;
|
|||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use anyhow::{Result, anyhow};
|
||||
use chrono::DateTime;
|
||||
use collections::HashSet;
|
||||
|
@ -322,8 +323,8 @@ impl TryFrom<ApiTokenResponse> for ApiToken {
|
|||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(response: ApiTokenResponse) -> Result<Self, Self::Error> {
|
||||
let expires_at = DateTime::from_timestamp(response.expires_at, 0)
|
||||
.ok_or_else(|| anyhow!("invalid expires_at"))?;
|
||||
let expires_at =
|
||||
DateTime::from_timestamp(response.expires_at, 0).context("invalid expires_at")?;
|
||||
|
||||
Ok(Self {
|
||||
api_key: response.token,
|
||||
|
@ -442,9 +443,11 @@ impl CopilotChat {
|
|||
request: Request,
|
||||
mut cx: AsyncApp,
|
||||
) -> Result<BoxStream<'static, Result<ResponseEvent>>> {
|
||||
let Some(this) = cx.update(|cx| Self::global(cx)).ok().flatten() else {
|
||||
return Err(anyhow!("Copilot chat is not enabled"));
|
||||
};
|
||||
let this = cx
|
||||
.update(|cx| Self::global(cx))
|
||||
.ok()
|
||||
.flatten()
|
||||
.context("Copilot chat is not enabled")?;
|
||||
|
||||
let (oauth_token, api_token, client) = this.read_with(&cx, |this, _| {
|
||||
(
|
||||
|
@ -454,7 +457,7 @@ impl CopilotChat {
|
|||
)
|
||||
})?;
|
||||
|
||||
let oauth_token = oauth_token.ok_or_else(|| anyhow!("No OAuth token available"))?;
|
||||
let oauth_token = oauth_token.context("No OAuth token available")?;
|
||||
|
||||
let token = match api_token {
|
||||
Some(api_token) if api_token.remaining_seconds() > 5 * 60 => api_token.clone(),
|
||||
|
@ -513,18 +516,19 @@ async fn request_models(api_token: String, client: Arc<dyn HttpClient>) -> Resul
|
|||
|
||||
let mut response = client.send(request).await?;
|
||||
|
||||
if response.status().is_success() {
|
||||
let mut body = Vec::new();
|
||||
response.body_mut().read_to_end(&mut body).await?;
|
||||
anyhow::ensure!(
|
||||
response.status().is_success(),
|
||||
"Failed to request models: {}",
|
||||
response.status()
|
||||
);
|
||||
let mut body = Vec::new();
|
||||
response.body_mut().read_to_end(&mut body).await?;
|
||||
|
||||
let body_str = std::str::from_utf8(&body)?;
|
||||
let body_str = std::str::from_utf8(&body)?;
|
||||
|
||||
let models = serde_json::from_str::<ModelSchema>(body_str)?.data;
|
||||
let models = serde_json::from_str::<ModelSchema>(body_str)?.data;
|
||||
|
||||
Ok(models)
|
||||
} else {
|
||||
Err(anyhow!("Failed to request models: {}", response.status()))
|
||||
}
|
||||
Ok(models)
|
||||
}
|
||||
|
||||
async fn request_api_token(oauth_token: &str, client: Arc<dyn HttpClient>) -> Result<ApiToken> {
|
||||
|
@ -551,8 +555,7 @@ async fn request_api_token(oauth_token: &str, client: Arc<dyn HttpClient>) -> Re
|
|||
response.body_mut().read_to_end(&mut body).await?;
|
||||
|
||||
let body_str = std::str::from_utf8(&body)?;
|
||||
|
||||
Err(anyhow!("Failed to request API token: {}", body_str))
|
||||
anyhow::bail!("Failed to request API token: {body_str}");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -603,11 +606,11 @@ async fn stream_completion(
|
|||
let mut body = Vec::new();
|
||||
response.body_mut().read_to_end(&mut body).await?;
|
||||
let body_str = std::str::from_utf8(&body)?;
|
||||
return Err(anyhow!(
|
||||
anyhow::bail!(
|
||||
"Failed to connect to API: {} {}",
|
||||
response.status(),
|
||||
body_str
|
||||
));
|
||||
);
|
||||
}
|
||||
|
||||
if is_streaming {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue