Skip to content

Added #[track_caller] and Improved Debug message for unwrap_throw() #2995

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

Merged
merged 11 commits into from
May 11, 2023
Merged
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
17 changes: 16 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1309,17 +1309,31 @@ pub fn anyref_heap_live_count() -> u32 {
pub trait UnwrapThrowExt<T>: Sized {
/// Unwrap this `Option` or `Result`, but instead of panicking on failure,
/// throw an exception to JavaScript.
#[cfg_attr(debug_assertions, track_caller)]
fn unwrap_throw(self) -> T {
self.expect_throw("`unwrap_throw` failed")
if cfg!(all(debug_assertions, feature = "std")) {
let loc = core::panic::Location::caller();
let msg = std::format!(
"`unwrap_throw` failed ({}:{}:{})",
loc.file(),
loc.line(),
loc.column()
);
self.expect_throw(&msg)
} else {
self.expect_throw("`unwrap_throw` failed")
}
}

/// Unwrap this container's `T` value, or throw an error to JS with the
/// given message if the `T` value is unavailable (e.g. an `Option<T>` is
/// `None`).
#[cfg_attr(debug_assertions, track_caller)]
fn expect_throw(self, message: &str) -> T;
}

impl<T> UnwrapThrowExt<T> for Option<T> {
#[cfg_attr(debug_assertions, track_caller)]
fn expect_throw(self, message: &str) -> T {
if cfg!(all(target_arch = "wasm32", not(target_os = "emscripten"))) {
match self {
Expand All @@ -1336,6 +1350,7 @@ impl<T, E> UnwrapThrowExt<T> for Result<T, E>
where
E: core::fmt::Debug,
{
#[cfg_attr(debug_assertions, track_caller)]
fn expect_throw(self, message: &str) -> T {
if cfg!(all(target_arch = "wasm32", not(target_os = "emscripten"))) {
match self {
Expand Down