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:
Kirill Bulatov 2025-05-21 02:06:07 +03:00 committed by GitHub
parent 1e51a7ac44
commit 16366cf9f2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
294 changed files with 2037 additions and 2610 deletions

View file

@ -351,14 +351,7 @@ impl RunningKernel for NativeRunningKernel {
fn force_shutdown(&mut self, _window: &mut Window, _cx: &mut App) -> Task<anyhow::Result<()>> {
self._process_status_task.take();
self.request_tx.close_channel();
Task::ready(match self.process.kill() {
Ok(_) => Ok(()),
Err(error) => Err(anyhow::anyhow!(
"Failed to kill the kernel process: {}",
error
)),
})
Task::ready(self.process.kill().context("killing the kernel process"))
}
}

View file

@ -54,7 +54,7 @@ pub async fn launch_remote_kernel(
if !response.status().is_success() {
let mut body = String::new();
response.into_body().read_to_string(&mut body).await?;
return Err(anyhow::anyhow!("Failed to launch kernel: {}", body));
anyhow::bail!("Failed to launch kernel: {body}");
}
let mut body = String::new();
@ -79,36 +79,31 @@ pub async fn list_remote_kernelspecs(
let response = http_client.send(request).await?;
if response.status().is_success() {
let mut body = response.into_body();
anyhow::ensure!(
response.status().is_success(),
"Failed to fetch kernel specs: {}",
response.status()
);
let mut body = response.into_body();
let mut body_bytes = Vec::new();
body.read_to_end(&mut body_bytes).await?;
let mut body_bytes = Vec::new();
body.read_to_end(&mut body_bytes).await?;
let kernel_specs: KernelSpecsResponse = serde_json::from_slice(&body_bytes)?;
let kernel_specs: KernelSpecsResponse = serde_json::from_slice(&body_bytes)?;
let remote_kernelspecs = kernel_specs
.kernelspecs
.into_iter()
.map(|(name, spec)| RemoteKernelSpecification {
name: name.clone(),
url: remote_server.base_url.clone(),
token: remote_server.token.clone(),
kernelspec: spec.spec,
})
.collect::<Vec<RemoteKernelSpecification>>();
let remote_kernelspecs = kernel_specs
.kernelspecs
.into_iter()
.map(|(name, spec)| RemoteKernelSpecification {
name: name.clone(),
url: remote_server.base_url.clone(),
token: remote_server.token.clone(),
kernelspec: spec.spec,
})
.collect::<Vec<RemoteKernelSpecification>>();
if remote_kernelspecs.is_empty() {
Err(anyhow::anyhow!("No kernel specs found"))
} else {
Ok(remote_kernelspecs.clone())
}
} else {
Err(anyhow::anyhow!(
"Failed to fetch kernel specs: {}",
response.status()
))
}
anyhow::ensure!(!remote_kernelspecs.is_empty(), "No kernel specs found");
Ok(remote_kernelspecs.clone())
}
impl PartialEq for RemoteKernelSpecification {
@ -288,14 +283,12 @@ impl RunningKernel for RemoteRunningKernel {
let response = http_client.send(request).await?;
if response.status().is_success() {
Ok(())
} else {
Err(anyhow::anyhow!(
"Failed to shutdown kernel: {}",
response.status()
))
}
anyhow::ensure!(
response.status().is_success(),
"Failed to shutdown kernel: {}",
response.status()
);
Ok(())
})
}
}

View file

@ -565,7 +565,7 @@ impl project::ProjectItem for NotebookItem {
project: &Entity<Project>,
path: &ProjectPath,
cx: &mut App,
) -> Option<Task<gpui::Result<Entity<Self>>>> {
) -> Option<Task<anyhow::Result<Entity<Self>>>> {
let path = path.clone();
let project = project.clone();
let fs = project.read(cx).fs().clone();
@ -575,7 +575,7 @@ impl project::ProjectItem for NotebookItem {
Some(cx.spawn(async move |cx| {
let abs_path = project
.read_with(cx, |project, cx| project.absolute_path(&path, cx))?
.ok_or_else(|| anyhow::anyhow!("Failed to find the absolute path"))?;
.with_context(|| format!("finding the absolute path of {path:?}"))?;
// todo: watch for changes to the file
let file_content = fs.load(&abs_path.as_path()).await?;

View file

@ -51,8 +51,8 @@ impl ImageView {
image::ImageFormat::WebP => ImageFormat::Webp,
image::ImageFormat::Tiff => ImageFormat::Tiff,
image::ImageFormat::Bmp => ImageFormat::Bmp,
_ => {
return Err(anyhow::anyhow!("unsupported image format"));
format => {
anyhow::bail!("unsupported image format {format:?}");
}
};

View file

@ -107,7 +107,7 @@ pub fn run(
let kernel_specification = store
.read(cx)
.active_kernelspec(project_path.worktree_id, Some(language.clone()), cx)
.ok_or_else(|| anyhow::anyhow!("No kernel found for language: {}", language.name()))?;
.with_context(|| format!("No kernel found for language: {}", language.name()))?;
let fs = store.read(cx).fs().clone();

View file

@ -1,6 +1,6 @@
use std::sync::Arc;
use anyhow::Result;
use anyhow::{Context as _, Result};
use collections::HashMap;
use command_palette_hooks::CommandPaletteFilter;
use gpui::{App, Context, Entity, EntityId, Global, Subscription, Task, prelude::*};
@ -125,7 +125,7 @@ impl ReplStore {
cx.spawn(async move |this, cx| {
let kernel_specifications = kernel_specifications
.await
.map_err(|e| anyhow::anyhow!("Failed to get python kernelspecs: {:?}", e))?;
.context("getting python kernelspecs")?;
this.update(cx, |this, cx| {
this.kernel_specifications_for_worktree

View file

@ -6,6 +6,7 @@ use crate::{
kernels::{Kernel, KernelSpecification, NativeRunningKernel},
outputs::{ExecutionStatus, ExecutionView},
};
use anyhow::Context as _;
use collections::{HashMap, HashSet};
use editor::{
Anchor, AnchorRangeExt as _, Editor, MultiBuffer, ToPoint,
@ -57,13 +58,8 @@ impl EditorBlock {
on_close: CloseBlockFn,
cx: &mut Context<Session>,
) -> anyhow::Result<Self> {
let editor = editor
.upgrade()
.ok_or_else(|| anyhow::anyhow!("editor is not open"))?;
let workspace = editor
.read(cx)
.workspace()
.ok_or_else(|| anyhow::anyhow!("workspace dropped"))?;
let editor = editor.upgrade().context("editor is not open")?;
let workspace = editor.read(cx).workspace().context("workspace dropped")?;
let execution_view = cx.new(|cx| ExecutionView::new(status, workspace.downgrade(), cx));