Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add helping log when trying to access an entity that does not exist #1712

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions crates/bevy_ecs/src/entity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,15 @@ pub struct Entities {
len: u32,
}

/// Error getting the location of an entity.
#[derive(Debug)]
pub enum EntityLocationError {
/// This entity has not yet been spawned.
NotYetSpawned,
/// This entity has already been despawned.
AlreadyDespawned,
}

impl Entities {
/// Reserve entity IDs concurrently
///
Expand Down Expand Up @@ -353,15 +362,16 @@ impl Entities {
}

/// Returns `Ok(Location { archetype: 0, index: undefined })` for pending entities
pub fn get(&self, entity: Entity) -> Option<EntityLocation> {
pub fn get(&self, entity: Entity) -> Result<EntityLocation, EntityLocationError> {
if (entity.id as usize) < self.meta.len() {
let meta = &self.meta[entity.id as usize];
if meta.generation != entity.generation {
return None;
match meta.generation.cmp(&entity.generation) {
std::cmp::Ordering::Equal => Ok(meta.location),
std::cmp::Ordering::Less => Err(EntityLocationError::NotYetSpawned),
std::cmp::Ordering::Greater => Err(EntityLocationError::AlreadyDespawned),
}
Some(meta.location)
} else {
None
Err(EntityLocationError::NotYetSpawned)
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_ecs/src/query/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ where
let location = world
.entities
.get(entity)
.ok_or(QueryEntityError::NoSuchEntity)?;
.map_err(|_| QueryEntityError::NoSuchEntity)?;
if !self
.matched_archetypes
.contains(location.archetype_id.index())
Expand Down
23 changes: 18 additions & 5 deletions crates/bevy_ecs/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::{
query::{FilterFetch, QueryState, WorldQuery},
storage::{Column, SparseSet, Storages},
};
use bevy_utils::tracing::warn;
use std::{
any::TypeId,
fmt,
Expand Down Expand Up @@ -237,7 +238,13 @@ impl World {
/// ```
#[inline]
pub fn get_entity(&self, entity: Entity) -> Option<EntityRef> {
let location = self.entities.get(entity)?;
let location = match self.entities.get(entity) {
Ok(entity_location) => entity_location,
Err(err) => {
warn!("Error getting entity {:?}: {:?}", entity, err,);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think warn! is a too strong log level. The user may very well just not care about if the entity exists or not. I think it would be better to return Result<EntityRef, GetEntityError> where GetEntityError has a Debug implementation that shows all this information.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree. This method feels too "low level" and could be called in too many different situations to call this case a warning / make it unrecoverable. I'd prefer to preserve the simplicity of the Option return type (like std's collection types) if possible, but if we really need to expose multiple "failure" states, it probably makes sense to just return an error here.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I... can't remember why I wanted a warn here :(
I could weakly argue that the user should not ignore this, but the Option already achieve that.

For the error reason, I think knowing it can help the user debug issues looking at the log but is not very useful from the code. Should I change the log to info or debug?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I honestly don't want to log at all here. If some subset of users need to care about the various reasons an entity might not exist, then imo we need to return a Result here.

return None;
}
};
Some(EntityRef::new(self, entity, location))
}

Expand All @@ -264,7 +271,13 @@ impl World {
/// ```
#[inline]
pub fn get_entity_mut(&mut self, entity: Entity) -> Option<EntityMut> {
let location = self.entities.get(entity)?;
let location = match self.entities.get(entity) {
Ok(entity_location) => entity_location,
Err(err) => {
warn!("Error getting entity {:?}: {:?}", entity, err,);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
warn!("Error getting entity {:?}: {:?}", entity, err,);
warn!("Error getting entity {:?}: {:?}", entity, err);

I think this trailing comma is here by mistake?

return None;
}
};
// SAFE: `entity` exists and `location` is that entity's location
Some(unsafe { EntityMut::new(self, entity, location) })
}
Expand Down Expand Up @@ -431,15 +444,15 @@ impl World {
///
/// let mut world = World::new();
/// let entities = world.spawn_batch(vec![
/// (Position { x: 0.0, y: 0.0}, Velocity { x: 1.0, y: 0.0 }),
/// (Position { x: 0.0, y: 0.0}, Velocity { x: 0.0, y: 1.0 }),
/// (Position { x: 0.0, y: 0.0}, Velocity { x: 1.0, y: 0.0 }),
/// (Position { x: 0.0, y: 0.0}, Velocity { x: 0.0, y: 1.0 }),
/// ]).collect::<Vec<Entity>>();
///
/// let mut query = world.query::<(&mut Position, &Velocity)>();
/// for (mut position, velocity) in query.iter_mut(&mut world) {
/// position.x += velocity.x;
/// position.y += velocity.y;
/// }
/// }
///
/// assert_eq!(world.get::<Position>(entities[0]).unwrap(), &Position { x: 1.0, y: 0.0 });
/// assert_eq!(world.get::<Position>(entities[1]).unwrap(), &Position { x: 0.0, y: 1.0 });
Expand Down