Skip to content

Commit c9e1fcd

Browse files
Added AssetLoadFailedEvent, UntypedAssetLoadFailedEvent (#11369)
# Objective This adds events for assets that fail to load along with minor utility methods to make them useful. This paves the way for users writing their own error handling and retry systems, plus Bevy including robust retry handling: #11349. * Addresses #11288 * Needed for #11349 # Solution ```rust /// An event emitted when a specific [`Asset`] fails to load. #[derive(Event, Clone, Debug)] pub struct AssetLoadFailedEvent<A: Asset> { pub id: AssetId<A>, /// The original handle returned when the asset load was requested. pub handle: Option<Handle<A>>, /// The asset path that was attempted. pub path: AssetPath<'static>, /// Why the asset failed to load. pub error: AssetLoadError, } ``` I started implementing `AssetEvent::Failed` like suggested in #11288, but decided it was better as its own type because: * I think it makes sense for `AssetEvent` to only refer to assets that actually exist. * In order to return `AssetLoadError` in the event (which is useful information for error handlers that might attempt a retry) we would have to remove `Copy` from `AssetEvent`. * There are numerous places in the render app that match against `AssetEvent`, and I don't think it's worth introducing extra noise about assets that don't exist. I also introduced `UntypedAssetLoadErrorEvent`, which is very useful in places that need to support type flexibility, like an Asset-agnostic retry plugin. # Changelog * **Added:** `AssetLoadFailedEvent<A>` * **Added**: `UntypedAssetLoadFailedEvent` * **Added:** `AssetReaderError::Http` for status code information on HTTP errors. Before this, status codes were only available by parsing the error message of generic `Io` errors. * **Added:** `asset_server.get_path_id(path)`. This method simply gets the asset id for the path. Without this, one was left using `get_path_handle(path)`, which has the overhead of returning a strong handle. * **Fixed**: Made `AssetServer` loads return the same handle for assets that already exist in a failed state. Now, when you attempt a `load` that's in a `LoadState::Failed` state, it'll re-use the original asset id. The advantage of this is that any dependent assets created using the original handle will "unbreak" if a retry succeeds. --------- Co-authored-by: Alice Cecile <[email protected]>
1 parent 9abf565 commit c9e1fcd

File tree

9 files changed

+411
-54
lines changed

9 files changed

+411
-54
lines changed

crates/bevy_asset/src/event.rs

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,47 @@
1-
use crate::{Asset, AssetId};
1+
use crate::{Asset, AssetId, AssetLoadError, AssetPath, UntypedAssetId};
22
use bevy_ecs::event::Event;
33
use std::fmt::Debug;
44

5-
/// Events that occur for a specific [`Asset`], such as "value changed" events and "dependency" events.
5+
/// An event emitted when a specific [`Asset`] fails to load.
6+
///
7+
/// For an untyped equivalent, see [`UntypedAssetLoadFailedEvent`].
8+
#[derive(Event, Clone, Debug)]
9+
pub struct AssetLoadFailedEvent<A: Asset> {
10+
pub id: AssetId<A>,
11+
/// The asset path that was attempted.
12+
pub path: AssetPath<'static>,
13+
/// Why the asset failed to load.
14+
pub error: AssetLoadError,
15+
}
16+
17+
impl<A: Asset> AssetLoadFailedEvent<A> {
18+
/// Converts this to an "untyped" / "generic-less" asset error event that stores the type information.
19+
pub fn untyped(&self) -> UntypedAssetLoadFailedEvent {
20+
self.into()
21+
}
22+
}
23+
24+
/// An untyped version of [`AssetLoadFailedEvent`].
25+
#[derive(Event, Clone, Debug)]
26+
pub struct UntypedAssetLoadFailedEvent {
27+
pub id: UntypedAssetId,
28+
/// The asset path that was attempted.
29+
pub path: AssetPath<'static>,
30+
/// Why the asset failed to load.
31+
pub error: AssetLoadError,
32+
}
33+
34+
impl<A: Asset> From<&AssetLoadFailedEvent<A>> for UntypedAssetLoadFailedEvent {
35+
fn from(value: &AssetLoadFailedEvent<A>) -> Self {
36+
UntypedAssetLoadFailedEvent {
37+
id: value.id.untyped(),
38+
path: value.path.clone(),
39+
error: value.error.clone(),
40+
}
41+
}
42+
}
43+
44+
/// Events that occur for a specific loaded [`Asset`], such as "value changed" events and "dependency" events.
645
#[derive(Event)]
746
pub enum AssetEvent<A: Asset> {
847
/// Emitted whenever an [`Asset`] is added.

crates/bevy_asset/src/io/mod.rs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,32 @@ use futures_lite::{ready, Stream};
2727
use std::{
2828
path::{Path, PathBuf},
2929
pin::Pin,
30+
sync::Arc,
3031
task::Poll,
3132
};
3233
use thiserror::Error;
3334

3435
/// Errors that occur while loading assets.
35-
#[derive(Error, Debug)]
36+
#[derive(Error, Debug, Clone)]
3637
pub enum AssetReaderError {
3738
/// Path not found.
38-
#[error("path not found: {0}")]
39+
#[error("Path not found: {0}")]
3940
NotFound(PathBuf),
4041

4142
/// Encountered an I/O error while loading an asset.
42-
#[error("encountered an io error while loading asset: {0}")]
43-
Io(#[from] std::io::Error),
43+
#[error("Encountered an I/O error while loading asset: {0}")]
44+
Io(Arc<std::io::Error>),
45+
46+
/// The HTTP request completed but returned an unhandled [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).
47+
/// If the request fails before getting a status code (e.g. request timeout, interrupted connection, etc), expect [`AssetReaderError::Io`].
48+
#[error("Encountered HTTP status {0:?} when loading asset")]
49+
HttpError(u16),
50+
}
51+
52+
impl From<std::io::Error> for AssetReaderError {
53+
fn from(value: std::io::Error) -> Self {
54+
Self::Io(Arc::new(value))
55+
}
4456
}
4557

4658
pub type Reader<'a> = dyn AsyncRead + Unpin + Send + Sync + 'a;

crates/bevy_asset/src/io/source.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -569,22 +569,22 @@ impl AssetSources {
569569
}
570570

571571
/// An error returned when an [`AssetSource`] does not exist for a given id.
572-
#[derive(Error, Debug)]
572+
#[derive(Error, Debug, Clone)]
573573
#[error("Asset Source '{0}' does not exist")]
574574
pub struct MissingAssetSourceError(AssetSourceId<'static>);
575575

576576
/// An error returned when an [`AssetWriter`] does not exist for a given id.
577-
#[derive(Error, Debug)]
577+
#[derive(Error, Debug, Clone)]
578578
#[error("Asset Source '{0}' does not have an AssetWriter.")]
579579
pub struct MissingAssetWriterError(AssetSourceId<'static>);
580580

581581
/// An error returned when a processed [`AssetReader`] does not exist for a given id.
582-
#[derive(Error, Debug)]
582+
#[derive(Error, Debug, Clone)]
583583
#[error("Asset Source '{0}' does not have a processed AssetReader.")]
584584
pub struct MissingProcessedAssetReaderError(AssetSourceId<'static>);
585585

586586
/// An error returned when a processed [`AssetWriter`] does not exist for a given id.
587-
#[derive(Error, Debug)]
587+
#[derive(Error, Debug, Clone)]
588588
#[error("Asset Source '{0}' does not have a processed AssetWriter.")]
589589
pub struct MissingProcessedAssetWriterError(AssetSourceId<'static>);
590590

crates/bevy_asset/src/io/wasm.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,7 @@ impl HttpWasmAssetReader {
5353
Ok(reader)
5454
}
5555
404 => Err(AssetReaderError::NotFound(path)),
56-
status => Err(AssetReaderError::Io(std::io::Error::new(
57-
std::io::ErrorKind::Other,
58-
format!("Encountered unexpected HTTP status {status}"),
59-
))),
56+
status => Err(AssetReaderError::HttpError(status as u16)),
6057
}
6158
}
6259
}

0 commit comments

Comments
 (0)