diff --git a/.changes/enhance-state-panic-message.md b/.changes/enhance-state-panic-message.md new file mode 100644 index 000000000000..9292143b48c1 --- /dev/null +++ b/.changes/enhance-state-panic-message.md @@ -0,0 +1,5 @@ +--- +"tauri": patch:enhance +--- + +Enhance panic message when fetching unmanaged state. diff --git a/crates/tauri/src/lib.rs b/crates/tauri/src/lib.rs index 318ceab56da3..1169c087b565 100644 --- a/crates/tauri/src/lib.rs +++ b/crates/tauri/src/lib.rs @@ -738,11 +738,12 @@ pub trait Manager: sealed::ManagerBase { where T: Send + Sync + 'static, { - self - .manager() - .state - .try_get() - .expect("state() called before manage() for given type") + self.manager().state.try_get().unwrap_or_else(|| { + panic!( + "state() called before manage() for {}", + std::any::type_name::() + ) + }) } /// Attempts to retrieve the managed state for the type `T`. diff --git a/crates/tauri/src/state.rs b/crates/tauri/src/state.rs index 36ebc24de722..74e6651c6ebb 100644 --- a/crates/tauri/src/state.rs +++ b/crates/tauri/src/state.rs @@ -153,7 +153,7 @@ impl StateManager { pub fn get(&self) -> State<'_, T> { self .try_get() - .expect("state: get() when given type is not managed") + .unwrap_or_else(|| panic!("state not found for type {}", std::any::type_name::())) } /// Gets the state associated with the specified type. @@ -191,6 +191,13 @@ mod tests { } } + #[test] + #[should_panic(expected = "state not found for type core::option::Option")] + fn get_panics() { + let state = StateManager::new(); + state.get::>(); + } + #[test] fn simple_set_get() { let state = StateManager::new();