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

@ -1,4 +1,5 @@
use super::*;
use anyhow::Context as _;
use sea_orm::sea_query::Query;
impl Database {
@ -51,7 +52,7 @@ impl Database {
Ok(access_token::Entity::find_by_id(access_token_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such access token"))?)
.context("no such access token")?)
})
.await
}

View file

@ -1,3 +1,5 @@
use anyhow::Context as _;
use super::*;
#[derive(Debug)]
@ -82,7 +84,7 @@ impl Database {
Ok(preferences
.into_iter()
.next()
.ok_or_else(|| anyhow!("billing preferences not found"))?)
.context("billing preferences not found")?)
})
.await
}

View file

@ -1,3 +1,5 @@
use anyhow::Context as _;
use crate::db::billing_subscription::{
StripeCancellationReason, StripeSubscriptionStatus, SubscriptionKind,
};
@ -51,7 +53,7 @@ impl Database {
Ok(billing_subscription::Entity::find_by_id(id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("failed to retrieve inserted billing subscription"))?)
.context("failed to retrieve inserted billing subscription")?)
})
.await
}

View file

@ -1,4 +1,5 @@
use super::*;
use anyhow::Context as _;
use prost::Message;
use text::{EditOperation, UndoOperation};
@ -467,7 +468,7 @@ impl Database {
.filter(buffer::Column::ChannelId.eq(channel_id))
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such buffer"))?;
.context("no such buffer")?;
let serialization_version = self
.get_buffer_operation_serialization_version(buffer.id, buffer.epoch, &tx)
@ -606,7 +607,7 @@ impl Database {
.into_values::<_, QueryOperationSerializationVersion>()
.one(tx)
.await?
.ok_or_else(|| anyhow!("missing buffer snapshot"))?)
.context("missing buffer snapshot")?)
}
pub async fn get_channel_buffer(
@ -621,7 +622,7 @@ impl Database {
.find_related(buffer::Entity)
.one(tx)
.await?
.ok_or_else(|| anyhow!("no such buffer"))?)
.context("no such buffer")?)
}
async fn get_buffer_state(
@ -643,7 +644,7 @@ impl Database {
)
.one(tx)
.await?
.ok_or_else(|| anyhow!("no such snapshot"))?;
.context("no such snapshot")?;
let version = snapshot.operation_serialization_version;
(snapshot.text, version)
@ -839,7 +840,7 @@ fn operation_from_storage(
_format_version: i32,
) -> Result<proto::operation::Variant, Error> {
let operation =
storage::Operation::decode(row.value.as_slice()).map_err(|error| anyhow!("{}", error))?;
storage::Operation::decode(row.value.as_slice()).map_err(|error| anyhow!("{error}"))?;
let version = version_from_storage(&operation.version);
Ok(if operation.is_undo {
proto::operation::Variant::Undo(proto::operation::Undo {

View file

@ -1,4 +1,5 @@
use super::*;
use anyhow::Context as _;
use rpc::{
ErrorCode, ErrorCodeExt,
proto::{ChannelBufferVersion, VectorClockEntry, channel_member::Kind},
@ -647,11 +648,8 @@ impl Database {
.and(channel_member::Column::UserId.eq(for_user)),
)
.one(&*tx)
.await?;
let Some(membership) = membership else {
Err(anyhow!("no such member"))?
};
.await?
.context("no such member")?;
let mut update = membership.into_active_model();
update.role = ActiveValue::Set(role);

View file

@ -1,3 +1,5 @@
use anyhow::Context as _;
use super::*;
impl Database {
@ -215,7 +217,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such contact"))?;
.context("no such contact")?;
contact::Entity::delete_by_id(contact.id).exec(&*tx).await?;

View file

@ -1,5 +1,6 @@
use std::str::FromStr;
use anyhow::Context;
use chrono::Utc;
use sea_orm::sea_query::IntoCondition;
use util::ResultExt;
@ -166,7 +167,7 @@ impl Database {
.filter(extension::Column::ExternalId.eq(extension_id))
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such extension: {extension_id}"))?;
.with_context(|| format!("no such extension: {extension_id}"))?;
let extensions = [extension];
let mut versions = self
@ -274,7 +275,7 @@ impl Database {
.filter(extension::Column::ExternalId.eq(*external_id))
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("failed to insert extension"))?
.context("failed to insert extension")?
};
extension_version::Entity::insert_many(versions.iter().map(|version| {

View file

@ -1,4 +1,5 @@
use super::*;
use anyhow::Context as _;
use rpc::Notification;
use sea_orm::{SelectColumns, TryInsertResult};
use time::OffsetDateTime;
@ -330,7 +331,7 @@ impl Database {
.filter(channel_message::Column::Nonce.eq(Uuid::from_u128(nonce)))
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("failed to insert message"))?
.context("failed to insert message")?
.id;
}
}

View file

@ -1,4 +1,5 @@
use super::*;
use anyhow::Context as _;
use rpc::Notification;
use util::ResultExt;
@ -256,7 +257,7 @@ pub fn model_to_proto(this: &Database, row: notification::Model) -> Result<proto
let kind = this
.notification_kinds_by_id
.get(&row.kind)
.ok_or_else(|| anyhow!("Unknown notification kind"))?;
.context("Unknown notification kind")?;
Ok(proto::Notification {
id: row.id.to_proto(),
kind: kind.to_string(),
@ -276,5 +277,5 @@ fn notification_kind_from_proto(
.notification_kinds_by_name
.get(&proto.kind)
.copied()
.ok_or_else(|| anyhow!("invalid notification kind {:?}", proto.kind))?)
.with_context(|| format!("invalid notification kind {:?}", proto.kind))?)
}

View file

@ -49,7 +49,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("could not find participant"))?;
.context("could not find participant")?;
if participant.room_id != room_id {
return Err(anyhow!("shared project on unexpected room"))?;
}
@ -128,7 +128,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("project not found"))?;
.context("project not found")?;
let room = if let Some(room_id) = project.room_id {
Some(self.get_room(room_id, &tx).await?)
} else {
@ -160,7 +160,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
self.update_project_worktrees(project.id, worktrees, &tx)
.await?;
@ -242,7 +242,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project: {project_id}"))?;
.with_context(|| format!("no such project: {project_id}"))?;
// Update metadata.
worktree::Entity::update(worktree::ActiveModel {
@ -624,16 +624,13 @@ impl Database {
let project_id = ProjectId::from_proto(update.project_id);
let worktree_id = update.worktree_id as i64;
self.project_transaction(project_id, |tx| async move {
let summary = update
.summary
.as_ref()
.ok_or_else(|| anyhow!("invalid summary"))?;
let summary = update.summary.as_ref().context("invalid summary")?;
// Ensure the update comes from the host.
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
if project.host_connection()? != connection {
return Err(anyhow!("can't update a project hosted by someone else"))?;
}
@ -677,16 +674,13 @@ impl Database {
) -> Result<TransactionGuard<Vec<ConnectionId>>> {
let project_id = ProjectId::from_proto(update.project_id);
self.project_transaction(project_id, |tx| async move {
let server = update
.server
.as_ref()
.ok_or_else(|| anyhow!("invalid language server"))?;
let server = update.server.as_ref().context("invalid language server")?;
// Ensure the update comes from the host.
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
if project.host_connection()? != connection {
return Err(anyhow!("can't update a project hosted by someone else"))?;
}
@ -732,7 +726,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
if project.host_connection()? != connection {
return Err(anyhow!("can't update a project hosted by someone else"))?;
}
@ -778,7 +772,7 @@ impl Database {
Ok(project::Entity::find_by_id(id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?)
.context("no such project")?)
})
.await
}
@ -1074,7 +1068,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
let collaborators = project
.find_related(project_collaborator::Entity)
.all(&*tx)
@ -1143,7 +1137,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("failed to read project host"))?;
.context("failed to read project host")?;
Ok(())
})
@ -1162,7 +1156,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
let role_from_room = if let Some(room_id) = project.room_id {
room_participant::Entity::find()
@ -1287,7 +1281,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.context("no such project")?;
let mut collaborators = project_collaborator::Entity::find()
.filter(project_collaborator::Column::ProjectId.eq(project_id))

View file

@ -161,7 +161,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("user is not in the room"))?;
.context("user is not in the room")?;
let called_user_role = match caller.role.unwrap_or(ChannelRole::Member) {
ChannelRole::Admin | ChannelRole::Member => ChannelRole::Member,
@ -193,7 +193,7 @@ impl Database {
let room = self.get_room(room_id, &tx).await?;
let incoming_call = Self::build_incoming_call(&room, called_user_id)
.ok_or_else(|| anyhow!("failed to build incoming call"))?;
.context("failed to build incoming call")?;
Ok((room, incoming_call))
})
.await
@ -279,7 +279,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no call to cancel"))?;
.context("no call to cancel")?;
room_participant::Entity::delete(participant.into_active_model())
.exec(&*tx)
@ -310,7 +310,7 @@ impl Database {
.into_values::<_, QueryChannelId>()
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such room"))?;
.context("no such room")?;
if channel_id.is_some() {
Err(anyhow!("tried to join channel call directly"))?
@ -462,7 +462,7 @@ impl Database {
}
let (channel, room) = self.get_channel_room(room_id, tx).await?;
let channel = channel.ok_or_else(|| anyhow!("no channel for room"))?;
let channel = channel.context("no channel for room")?;
Ok(JoinRoom {
room,
channel: Some(channel),
@ -505,7 +505,7 @@ impl Database {
let project = project::Entity::find_by_id(project_id)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("project does not exist"))?;
.context("project does not exist")?;
if project.host_user_id != Some(user_id) {
return Err(anyhow!("no such project"))?;
}
@ -519,7 +519,7 @@ impl Database {
.position(|collaborator| {
collaborator.user_id == user_id && collaborator.is_host
})
.ok_or_else(|| anyhow!("host not found among collaborators"))?;
.context("host not found among collaborators")?;
let host = collaborators.swap_remove(host_ix);
let old_connection_id = host.connection();
@ -1051,11 +1051,7 @@ impl Database {
let tx = tx;
let location_kind;
let location_project_id;
match location
.variant
.as_ref()
.ok_or_else(|| anyhow!("invalid location"))?
{
match location.variant.as_ref().context("invalid location")? {
proto::participant_location::Variant::SharedProject(project) => {
location_kind = 0;
location_project_id = Some(ProjectId::from_proto(project.id));
@ -1119,7 +1115,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("only admins can set participant role"))?;
.context("only admins can set participant role")?;
if role.requires_cla() {
self.check_user_has_signed_cla(user_id, room_id, &tx)
@ -1156,7 +1152,7 @@ impl Database {
let channel = room::Entity::find_by_id(room_id)
.one(tx)
.await?
.ok_or_else(|| anyhow!("could not find room"))?
.context("could not find room")?
.find_related(channel::Entity)
.one(tx)
.await?;
@ -1297,7 +1293,7 @@ impl Database {
let db_room = room::Entity::find_by_id(room_id)
.one(tx)
.await?
.ok_or_else(|| anyhow!("could not find room"))?;
.context("could not find room")?;
let mut db_participants = db_room
.find_related(room_participant::Entity)

View file

@ -1,3 +1,4 @@
use anyhow::Context as _;
use chrono::NaiveDateTime;
use super::*;
@ -247,7 +248,7 @@ impl Database {
.into_values::<_, QueryAs>()
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("could not find user"))?;
.context("could not find user")?;
Ok(metrics_id.to_string())
})
.await

View file

@ -1,5 +1,5 @@
use crate::db::{ProjectId, Result, RoomId, ServerId, UserId};
use anyhow::anyhow;
use anyhow::Context as _;
use rpc::ConnectionId;
use sea_orm::entity::prelude::*;
@ -18,10 +18,10 @@ impl Model {
pub fn host_connection(&self) -> Result<ConnectionId> {
let host_connection_server_id = self
.host_connection_server_id
.ok_or_else(|| anyhow!("empty host_connection_server_id"))?;
.context("empty host_connection_server_id")?;
let host_connection_id = self
.host_connection_id
.ok_or_else(|| anyhow!("empty host_connection_id"))?;
.context("empty host_connection_id")?;
Ok(ConnectionId {
owner_id: host_connection_server_id.0 as u32,
id: host_connection_id as u32,