Replace RuntimeError::raise with RuntimeError::custom

This commit is contained in:
Amanieu d'Antras
2021-12-17 18:26:41 +01:00
parent 75e4cabe9b
commit 17c0834abf
7 changed files with 52 additions and 25 deletions

View File

@@ -644,6 +644,7 @@ impl wasmer_types::WasmValueType for Function {
/// This private inner module contains the low-level implementation
/// for `Function` and its siblings.
mod inner {
use super::RuntimeError;
use super::VMFunctionBody;
use std::array::TryFromSliceError;
use std::convert::{Infallible, TryInto};
@@ -1125,6 +1126,7 @@ mod inner {
}));
match result {
Ok(Ok(result)) => return result.into_c_struct(),
Ok(Err(trap)) => RuntimeError::raise(Box::new(trap)),
_ => unimplemented!(),
// Ok(Err(trap)) => unsafe { raise_user_trap(Box::new(trap)) },
// Err(panic) => unsafe { resume_panic(panic) },
@@ -1170,6 +1172,7 @@ mod inner {
}));
match result {
Ok(Ok(result)) => return result.into_c_struct(),
Ok(Err(trap)) => RuntimeError::raise(Box::new(trap)),
_ => unimplemented!(),
// Ok(Err(trap)) => unsafe { raise_user_trap(Box::new(trap)) },
// Err(panic) => unsafe { resume_panic(panic) },

View File

@@ -34,6 +34,10 @@ enum RuntimeErrorSource {
Js(JsValue),
}
/// This is a hack to ensure the error type is Send+Sync
unsafe impl Send for RuntimeErrorSource {}
unsafe impl Sync for RuntimeErrorSource {}
impl fmt::Display for RuntimeErrorSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@@ -58,26 +62,28 @@ impl RuntimeError {
}
}
/// Creates a new user `RuntimeError` with the given `error`.
pub fn user(error: impl Error + Send + Sync + 'static) -> Self {
RuntimeError {
inner: Arc::new(RuntimeErrorSource::User(Box::new(error))),
}
}
/// Raises a custom user Error
#[deprecated(since = "2.1.1", note = "prefer using RuntimeError::custom instead")]
pub fn raise(error: Box<dyn Error + Send + Sync>) -> ! {
let error = if error.is::<RuntimeError>() {
*error.downcast::<RuntimeError>().unwrap()
} else {
RuntimeError {
inner: Arc::new(RuntimeErrorSource::User(error)),
}
};
let error = Self::custom(error);
let js_error: JsValue = error.into();
wasm_bindgen::throw_val(js_error)
}
/// Creates a custom user Error.
///
/// This error object can be passed through Wasm frames and later retrieved
/// using the `downcast` method.
pub fn custom(error: Box<dyn Error + Send + Sync>) -> Self {
match error.downcast::<Self>() {
// The error is already a RuntimeError, we return it directly
Ok(runtime_error) => *runtime_error,
Err(error) => RuntimeError {
inner: Arc::new(RuntimeErrorSource::User(error)),
},
}
}
/// Returns a reference the `message` stored in `Trap`.
pub fn message(&self) -> String {
format!("{}", self.inner)