Skip to content

Commit

Permalink
Avoiding swallowing errors that arise in exported functions (#674)
Browse files Browse the repository at this point in the history
Similar to the main (`_start`) case, `eval_with_options` returns
a promise, which, needs to be explicitly inspected in order to retrieve
any values or any unhandled errors.

This commit ensures that the behaviour is the right one by inspecting
the underlying promise.
  • Loading branch information
saulecabrera authored Jun 21, 2024
1 parent 21e7c97 commit ef05dbd
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
19 changes: 19 additions & 0 deletions crates/cli/tests/dynamic_linking_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,25 @@ pub fn test_dynamic_linking_with_func_without_flag() -> Result<()> {
Ok(())
}

#[test]
fn test_errors_in_exported_functions_are_correctly_reported() -> Result<()> {
let js_src = "export function foo() { throw \"Error\" }";
let wit = "
package local:main
world foo-test {
export foo: func()
}
";
let res = invoke_fn_on_generated_module(js_src, "foo", Some((wit, "foo-test")), None, None);
assert!(res
.err()
.unwrap()
.to_string()
.contains("error while executing"));
Ok(())
}

#[test]
pub fn check_for_new_imports() -> Result<()> {
// If you need to change this test, then you've likely made a breaking change.
Expand Down
20 changes: 17 additions & 3 deletions crates/core/src/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,24 @@ pub fn invoke_function(runtime: &Runtime, fn_module: &str, fn_name: &str) {
let mut opts = EvalOptions::default();
opts.strict = false;
opts.global = false;
this.eval_with_options::<Value<'_>, _>(js, opts)
.map_err(|e| from_js_error(this.clone(), e))
.map(|_| ())
let value = this.eval_with_options::<Value<'_>, _>(js, opts)?;

if let Some(promise) = value.as_promise() {
if cfg!(feature = "experimental_event_loop") {
// If the experimental event loop is enabled, trigger it.
promise.finish::<Value>().map(|_| ())
} else {
// Else we simply expect the promise to resolve immediately.
match promise.result() {
None => Err(to_js_error(this, anyhow!(EVENT_LOOP_ERR))),
Some(r) => r,
}
}
} else {
Ok(())
}
})
.map_err(|e| runtime.context().with(|cx| from_js_error(cx.clone(), e)))
.and_then(|_: ()| process_event_loop(runtime))
.unwrap_or_else(handle_error)
}
Expand Down

0 comments on commit ef05dbd

Please sign in to comment.