fix(napi): improve error propagation ()

This commit is contained in:
Devon Govett 2022-09-14 02:03:11 -07:00 committed by GitHub
parent d5a6445bee
commit 5ba70b0e1a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 106 additions and 53 deletions
examples/napi-compat-mode

View file

@ -20,3 +20,14 @@ test('should set "this" properly', (t) => {
t.is(this, obj)
})
})
test('should handle errors', (t) => {
bindings.testCallFunctionError(
() => {
throw new Error('Testing')
},
(err: Error) => {
t.is(err.message, 'Testing')
},
)
})

View file

@ -1,4 +1,4 @@
use napi::{CallContext, JsFunction, JsNull, JsObject, Result};
use napi::{CallContext, JsError, JsFunction, JsNull, JsObject, JsUnknown, Result};
#[js_function(1)]
pub fn call_function(ctx: CallContext) -> Result<JsNull> {
@ -32,6 +32,17 @@ pub fn call_function_with_this(ctx: CallContext) -> Result<JsNull> {
ctx.env.get_null()
}
#[js_function(2)]
pub fn call_function_error(ctx: CallContext) -> Result<JsUnknown> {
let js_func = ctx.get::<JsFunction>(0)?;
let error_func = ctx.get::<JsFunction>(1)?;
match js_func.call_without_args(None) {
Ok(v) => Ok(v),
Err(e) => error_func.call(None, &[JsError::from(e).into_unknown(*ctx.env)]),
}
}
pub fn register_js(exports: &mut JsObject) -> Result<()> {
exports.create_named_method("testCallFunction", call_function)?;
exports.create_named_method(
@ -39,5 +50,6 @@ pub fn register_js(exports: &mut JsObject) -> Result<()> {
call_function_with_ref_arguments,
)?;
exports.create_named_method("testCallFunctionWithThis", call_function_with_this)?;
exports.create_named_method("testCallFunctionError", call_function_error)?;
Ok(())
}