Lines
100 %
Functions
65.63 %
Branches
//! Raising a catchable `$nomi_error` condition from a host fn.
use std::convert::Infallible;
use wasmtime::{AnyRef, AsContextMut, Caller, ExnRef, ExnRefPre, ExnType, Rooted, Val};
use super::abi::alloc_string_ref;
use super::decode::EvalValue;
use super::encode::alloc_value;
/// Throws a `$nomi_error` carrying `code` (upper-cased, as `handler-case` compares it),
/// `message` and the structured `detail`, so the calling script's `handler-case` can catch it
/// and read the detail with `error-detail`. Return the result from the host fn:
/// `return Err(throw_condition(&mut caller, code, message, &detail).await)`. Any failure while
/// building the condition is returned in its place.
pub async fn throw_condition<T: Send>(
caller: &mut Caller<'_, T>,
code: &str,
message: &str,
detail: &EvalValue,
) -> wasmtime::Error {
let exn = match build_exception(caller, &code.to_uppercase(), message, detail).await {
Ok(exn) => exn,
Err(err) => return err,
};
match caller.as_context_mut().throw::<Infallible>(exn) {
Err(thrown) => thrown,
}
async fn build_exception<T: Send>(
) -> wasmtime::Result<Rooted<ExnRef>> {
let tag = caller
.get_export("nomi_error")
.and_then(wasmtime::Extern::into_tag)
.ok_or_else(|| wasmtime::Error::msg("module does not export `nomi_error`"))?;
let condition = condition_new(caller, code, message, detail).await?;
let tag_type = tag.ty(&*caller);
let pre = ExnRefPre::new(caller.as_context_mut(), ExnType::from_tag_type(&tag_type)?);
ExnRef::new_async(
caller.as_context_mut(),
&pre,
&tag,
&[Val::AnyRef(Some(condition))],
)
.await
async fn condition_new<T: Send>(
) -> wasmtime::Result<Rooted<AnyRef>> {
let constructor = caller
.get_export("condition_new")
.and_then(wasmtime::Extern::into_func)
.ok_or_else(|| wasmtime::Error::msg("module does not export `condition_new`"))?;
let code = alloc_string_ref(caller, code.as_bytes())?;
let message = alloc_string_ref(caller, message.as_bytes())?;
let detail = alloc_value(caller, detail).await?;
let mut results = [Val::AnyRef(None)];
constructor
.call_async(
&[
Val::AnyRef(Some(code.to_anyref())),
Val::AnyRef(Some(message.to_anyref())),
Val::AnyRef(detail),
],
&mut results,
.await?;
match results {
[Val::AnyRef(Some(condition))] => Ok(condition),
_ => Err(wasmtime::Error::msg("condition_new returned no condition")),