From ad7f6d4510afc71ed40da1aa1ad649d59d3aef12 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Wed, 14 Apr 2021 23:11:39 +0200 Subject: [PATCH] fix(core): better "missing type" GothamState error (#10189) Include the type name in the error message so you know what to look for. --- core/gotham_state.rs | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/core/gotham_state.rs b/core/gotham_state.rs index b8f42137f5..4da8ac2786 100644 --- a/core/gotham_state.rs +++ b/core/gotham_state.rs @@ -4,6 +4,7 @@ // Copyright 2017 Gotham Project Developers. MIT license. use log::trace; +use std::any::type_name; use std::any::Any; use std::any::TypeId; use std::collections::BTreeMap; @@ -38,9 +39,7 @@ impl GothamState { /// Borrows a value from the `GothamState` storage. pub fn borrow(&self) -> &T { - self - .try_borrow() - .expect("required type is not present in GothamState container") + self.try_borrow().unwrap_or_else(|| missing::()) } /// Tries to mutably borrow a value from the `GothamState` storage. @@ -52,9 +51,7 @@ impl GothamState { /// Mutably borrows a value from the `GothamState` storage. pub fn borrow_mut(&mut self) -> &mut T { - self - .try_borrow_mut() - .expect("required type is not present in GothamState container") + self.try_borrow_mut().unwrap_or_else(|| missing::()) } /// Tries to move a value out of the `GothamState` storage and return ownership. @@ -77,12 +74,17 @@ impl GothamState { /// /// If a value of type `T` is not present in `GothamState`. pub fn take(&mut self) -> T { - self - .try_take() - .expect("required type is not present in GothamState container") + self.try_take().unwrap_or_else(|| missing::()) } } +fn missing() -> ! { + panic!( + "required type {} is not present in GothamState container", + type_name::() + ); +} + #[cfg(test)] mod tests { use super::GothamState; @@ -179,4 +181,13 @@ mod tests { assert!(state.try_take::().is_none()); assert!(state.try_take::().is_none()); } + + #[test] + #[should_panic( + expected = "required type deno_core::gotham_state::tests::MyStruct is not present in GothamState container" + )] + fn missing() { + let state = GothamState::default(); + let _ = state.borrow::(); + } }