use std::ffi::{c_int, c_void};
use std::ptr::null_mut;
use quickjspp::{Context, JSContext, OwnedJsValue, RawJSValue};
pub fn main() {
let context = Context::builder()
.console(|level, args| {
eprintln!("{}: {:?}", level, args);
})
.build()
.unwrap();
context.set_host_promise_rejection_tracker(Some(host_promise_rejection_tracker), null_mut());
let value = context.eval("1 + 2").unwrap();
println!("js: 1 + 2 = {:?}", value);
let ret = context.eval(
r#"
async function main() {
try {
// user code here
console.log("running");
throw Error("test");
} catch (e) {
await 1;
throw e;
}
}
// remove the catch block to see the error
main().catch((e) => {
console.log("err " + e);
});
"#,
);
if let Err(e) = ret {
eprintln!("Error: {:?}", e.to_string());
}
}
unsafe extern "C" fn host_promise_rejection_tracker(
ctx: *mut JSContext,
_promise: RawJSValue,
reason: RawJSValue,
is_handled: c_int,
_opaque: *mut c_void,
) {
let reason = OwnedJsValue::own(ctx, &reason);
println!(
"Promise rejection: {:?}, handled: {}",
reason.js_to_string(),
is_handled
);
}