1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-22 15:06:54 -05:00

fix(core): better "missing type" GothamState error (#10189)

Include the type name in the error message so you know what to look for.
This commit is contained in:
Ben Noordhuis 2021-04-14 23:11:39 +02:00 committed by GitHub
parent 353e79c796
commit ad7f6d4510
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -4,6 +4,7 @@
// Copyright 2017 Gotham Project Developers. MIT license. // Copyright 2017 Gotham Project Developers. MIT license.
use log::trace; use log::trace;
use std::any::type_name;
use std::any::Any; use std::any::Any;
use std::any::TypeId; use std::any::TypeId;
use std::collections::BTreeMap; use std::collections::BTreeMap;
@ -38,9 +39,7 @@ impl GothamState {
/// Borrows a value from the `GothamState` storage. /// Borrows a value from the `GothamState` storage.
pub fn borrow<T: 'static>(&self) -> &T { pub fn borrow<T: 'static>(&self) -> &T {
self self.try_borrow().unwrap_or_else(|| missing::<T>())
.try_borrow()
.expect("required type is not present in GothamState container")
} }
/// Tries to mutably borrow a value from the `GothamState` storage. /// Tries to mutably borrow a value from the `GothamState` storage.
@ -52,9 +51,7 @@ impl GothamState {
/// Mutably borrows a value from the `GothamState` storage. /// Mutably borrows a value from the `GothamState` storage.
pub fn borrow_mut<T: 'static>(&mut self) -> &mut T { pub fn borrow_mut<T: 'static>(&mut self) -> &mut T {
self self.try_borrow_mut().unwrap_or_else(|| missing::<T>())
.try_borrow_mut()
.expect("required type is not present in GothamState container")
} }
/// Tries to move a value out of the `GothamState` storage and return ownership. /// 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`. /// If a value of type `T` is not present in `GothamState`.
pub fn take<T: 'static>(&mut self) -> T { pub fn take<T: 'static>(&mut self) -> T {
self self.try_take().unwrap_or_else(|| missing::<T>())
.try_take()
.expect("required type is not present in GothamState container")
} }
} }
fn missing<T: 'static>() -> ! {
panic!(
"required type {} is not present in GothamState container",
type_name::<T>()
);
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::GothamState; use super::GothamState;
@ -179,4 +181,13 @@ mod tests {
assert!(state.try_take::<Alias1>().is_none()); assert!(state.try_take::<Alias1>().is_none());
assert!(state.try_take::<Alias2>().is_none()); assert!(state.try_take::<Alias2>().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::<MyStruct>();
}
} }