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
|
@ -1,5 +1,5 @@
|
|||
use ::fs::Fs;
|
||||
use anyhow::{Context as _, Result, anyhow};
|
||||
use anyhow::{Context as _, Result};
|
||||
use async_compression::futures::bufread::GzipDecoder;
|
||||
use async_tar::Archive;
|
||||
use async_trait::async_trait;
|
||||
|
@ -103,8 +103,8 @@ impl TcpArguments {
|
|||
pub fn from_proto(proto: proto::TcpHost) -> anyhow::Result<Self> {
|
||||
let host = TcpArgumentsTemplate::from_proto(proto)?;
|
||||
Ok(TcpArguments {
|
||||
host: host.host.ok_or_else(|| anyhow!("missing host"))?,
|
||||
port: host.port.ok_or_else(|| anyhow!("missing port"))?,
|
||||
host: host.host.context("missing host")?,
|
||||
port: host.port.context("missing port")?,
|
||||
timeout: host.timeout,
|
||||
})
|
||||
}
|
||||
|
@ -200,9 +200,7 @@ impl DebugTaskDefinition {
|
|||
}
|
||||
|
||||
pub fn from_proto(proto: proto::DebugTaskDefinition) -> Result<Self> {
|
||||
let request = proto
|
||||
.request
|
||||
.ok_or_else(|| anyhow::anyhow!("request is required"))?;
|
||||
let request = proto.request.context("request is required")?;
|
||||
Ok(Self {
|
||||
label: proto.label.into(),
|
||||
initialize_args: proto.initialize_args.map(|v| v.into()),
|
||||
|
@ -346,12 +344,11 @@ pub async fn download_adapter_from_github(
|
|||
.get(&github_version.url, Default::default(), true)
|
||||
.await
|
||||
.context("Error downloading release")?;
|
||||
if !response.status().is_success() {
|
||||
Err(anyhow!(
|
||||
"download failed with status {}",
|
||||
response.status().to_string()
|
||||
))?;
|
||||
}
|
||||
anyhow::ensure!(
|
||||
response.status().is_success(),
|
||||
"download failed with status {}",
|
||||
response.status().to_string()
|
||||
);
|
||||
|
||||
match file_type {
|
||||
DownloadedFileType::GzipTar => {
|
||||
|
|
|
@ -2,7 +2,7 @@ use crate::{
|
|||
adapters::DebugAdapterBinary,
|
||||
transport::{IoKind, LogKind, TransportDelegate},
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
use anyhow::Result;
|
||||
use dap_types::{
|
||||
messages::{Message, Response},
|
||||
requests::Request,
|
||||
|
@ -187,10 +187,7 @@ impl DebugAdapterClient {
|
|||
Ok(serde_json::from_value(Default::default())?)
|
||||
}
|
||||
}
|
||||
false => Err(anyhow!(
|
||||
"Request failed: {}",
|
||||
response.message.unwrap_or_default()
|
||||
)),
|
||||
false => anyhow::bail!("Request failed: {}", response.message.unwrap_or_default()),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
use anyhow::{Result, anyhow};
|
||||
use anyhow::{Context as _, Result};
|
||||
use client::proto::{
|
||||
self, DapChecksum, DapChecksumAlgorithm, DapEvaluateContext, DapModule, DapScope,
|
||||
DapScopePresentationHint, DapSource, DapSourcePresentationHint, DapStackFrame, DapVariable,
|
||||
|
@ -311,9 +311,9 @@ impl ProtoConversion for dap_types::Module {
|
|||
fn from_proto(payload: Self::ProtoType) -> Result<Self> {
|
||||
let id = match payload
|
||||
.id
|
||||
.ok_or(anyhow!("All DapModule proto messages must have an id"))?
|
||||
.context("All DapModule proto messages must have an id")?
|
||||
.id
|
||||
.ok_or(anyhow!("All DapModuleID proto messages must have an id"))?
|
||||
.context("All DapModuleID proto messages must have an id")?
|
||||
{
|
||||
proto::dap_module_id::Id::String(string) => dap_types::ModuleId::String(string),
|
||||
proto::dap_module_id::Id::Number(num) => dap_types::ModuleId::Number(num),
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use dap_types::{
|
||||
ErrorResponse,
|
||||
messages::{Message, Response},
|
||||
|
@ -226,12 +226,9 @@ impl TransportDelegate {
|
|||
|
||||
pub(crate) async fn send_message(&self, message: Message) -> Result<()> {
|
||||
if let Some(server_tx) = self.server_tx.lock().await.as_ref() {
|
||||
server_tx
|
||||
.send(message)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to send message: {}", e))
|
||||
server_tx.send(message).await.context("sending message")
|
||||
} else {
|
||||
Err(anyhow!("Server tx already dropped"))
|
||||
anyhow::bail!("Server tx already dropped")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -254,7 +251,7 @@ impl TransportDelegate {
|
|||
};
|
||||
|
||||
if bytes_read == 0 {
|
||||
break Err(anyhow!("Debugger log stream closed"));
|
||||
anyhow::bail!("Debugger log stream closed");
|
||||
}
|
||||
|
||||
if let Some(log_handlers) = log_handlers.as_ref() {
|
||||
|
@ -379,7 +376,7 @@ impl TransportDelegate {
|
|||
|
||||
let result = loop {
|
||||
match reader.read_line(&mut buffer).await {
|
||||
Ok(0) => break Err(anyhow!("debugger error stream closed")),
|
||||
Ok(0) => anyhow::bail!("debugger error stream closed"),
|
||||
Ok(_) => {
|
||||
for (kind, log_handler) in log_handlers.lock().iter_mut() {
|
||||
if matches!(kind, LogKind::Adapter) {
|
||||
|
@ -409,13 +406,13 @@ impl TransportDelegate {
|
|||
.and_then(|response| response.error.map(|msg| msg.format))
|
||||
.or_else(|| response.message.clone())
|
||||
{
|
||||
return Err(anyhow!(error_message));
|
||||
anyhow::bail!(error_message);
|
||||
};
|
||||
|
||||
Err(anyhow!(
|
||||
anyhow::bail!(
|
||||
"Received error response from adapter. Response: {:?}",
|
||||
response.clone()
|
||||
))
|
||||
response
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -437,7 +434,7 @@ impl TransportDelegate {
|
|||
.with_context(|| "reading a message from server")?
|
||||
== 0
|
||||
{
|
||||
return Err(anyhow!("debugger reader stream closed"));
|
||||
anyhow::bail!("debugger reader stream closed");
|
||||
};
|
||||
|
||||
if buffer == "\r\n" {
|
||||
|
@ -540,9 +537,10 @@ impl TcpTransport {
|
|||
}
|
||||
|
||||
async fn start(binary: &DebugAdapterBinary, cx: AsyncApp) -> Result<(TransportPipe, Self)> {
|
||||
let Some(connection_args) = binary.connection.as_ref() else {
|
||||
return Err(anyhow!("No connection arguments provided"));
|
||||
};
|
||||
let connection_args = binary
|
||||
.connection
|
||||
.as_ref()
|
||||
.context("No connection arguments provided")?;
|
||||
|
||||
let host = connection_args.host;
|
||||
let port = connection_args.port;
|
||||
|
@ -577,7 +575,7 @@ impl TcpTransport {
|
|||
|
||||
let (mut process, (rx, tx)) = select! {
|
||||
_ = cx.background_executor().timer(Duration::from_millis(timeout)).fuse() => {
|
||||
return Err(anyhow!(format!("Connection to TCP DAP timeout {}:{}", host, port)))
|
||||
anyhow::bail!("Connection to TCP DAP timeout {host}:{port}");
|
||||
},
|
||||
result = cx.spawn(async move |cx| {
|
||||
loop {
|
||||
|
@ -591,7 +589,7 @@ impl TcpTransport {
|
|||
} else {
|
||||
String::from_utf8_lossy(&output.stderr).to_string()
|
||||
};
|
||||
return Err(anyhow!("{}\nerror: process exited before debugger attached.", output));
|
||||
anyhow::bail!("{output}\nerror: process exited before debugger attached.");
|
||||
}
|
||||
cx.background_executor().timer(Duration::from_millis(100)).await;
|
||||
}
|
||||
|
@ -664,14 +662,8 @@ impl StdioTransport {
|
|||
.spawn()
|
||||
.with_context(|| "failed to spawn command.")?;
|
||||
|
||||
let stdin = process
|
||||
.stdin
|
||||
.take()
|
||||
.ok_or_else(|| anyhow!("Failed to open stdin"))?;
|
||||
let stdout = process
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| anyhow!("Failed to open stdout"))?;
|
||||
let stdin = process.stdin.take().context("Failed to open stdin")?;
|
||||
let stdout = process.stdout.take().context("Failed to open stdout")?;
|
||||
let stderr = process
|
||||
.stderr
|
||||
.take()
|
||||
|
@ -793,7 +785,7 @@ impl FakeTransport {
|
|||
|
||||
match message {
|
||||
Err(error) => {
|
||||
break anyhow!(error);
|
||||
break anyhow::anyhow!(error);
|
||||
}
|
||||
Ok(message) => {
|
||||
match message {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue