feat(napi): implement Env::throw to throw any JsValue
This commit is contained in:
parent
c92c5534c8
commit
e0671fe071
3 changed files with 32 additions and 1 deletions
|
@ -622,6 +622,11 @@ impl Env {
|
|||
unsafe { ptr::read(raw_extended_error) }.try_into()
|
||||
}
|
||||
|
||||
/// Throw any JavaScript value
|
||||
pub fn throw<T: NapiRaw>(&self, value: T) -> Result<()> {
|
||||
check_status!(unsafe { sys::napi_throw(self.0, value.raw()) })
|
||||
}
|
||||
|
||||
/// This API throws a JavaScript Error with the text provided.
|
||||
pub fn throw_error(&self, msg: &str, code: Option<&str>) -> Result<()> {
|
||||
check_status!(unsafe {
|
||||
|
|
|
@ -5,3 +5,14 @@ const bindings = require('../index.node')
|
|||
test('should be able to access env variable from native', (t) => {
|
||||
t.is(bindings.getEnvVariable(), 'napi-rs')
|
||||
})
|
||||
|
||||
test('should be able to throw syntax error', (t) => {
|
||||
const msg = 'Custom Syntax Error'
|
||||
try {
|
||||
bindings.throwSyntaxError(msg)
|
||||
throw new Error('Unreachable')
|
||||
} catch (e) {
|
||||
t.true(e instanceof SyntaxError)
|
||||
t.is((e as SyntaxError).message, msg)
|
||||
}
|
||||
})
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
use napi::{CallContext, ContextlessResult, Env, JsBoolean, JsObject, JsString, JsUnknown, Result};
|
||||
use napi::{
|
||||
CallContext, ContextlessResult, Env, JsBoolean, JsFunction, JsObject, JsString, JsUndefined,
|
||||
JsUnknown, Result,
|
||||
};
|
||||
|
||||
#[js_function(2)]
|
||||
pub fn instanceof(ctx: CallContext) -> Result<JsBoolean> {
|
||||
|
@ -39,6 +42,17 @@ fn get_env_variable(env: Env) -> ContextlessResult<JsString> {
|
|||
.map(Some)
|
||||
}
|
||||
|
||||
#[js_function(1)]
|
||||
pub fn throw_syntax_error(ctx: CallContext) -> Result<JsUndefined> {
|
||||
let message: JsString = ctx.get(0)?;
|
||||
let syntax_error = ctx
|
||||
.env
|
||||
.get_global()?
|
||||
.get_named_property::<JsFunction>("SyntaxError")?;
|
||||
ctx.env.throw(syntax_error.new(&[message])?)?;
|
||||
ctx.env.get_undefined()
|
||||
}
|
||||
|
||||
pub fn register_js(exports: &mut JsObject) -> Result<()> {
|
||||
exports.create_named_method("instanceof", instanceof)?;
|
||||
exports.create_named_method("isTypedarray", is_typedarray)?;
|
||||
|
@ -46,5 +60,6 @@ pub fn register_js(exports: &mut JsObject) -> Result<()> {
|
|||
exports.create_named_method("strictEquals", strict_equals)?;
|
||||
exports.create_named_method("castUnknown", cast_unknown)?;
|
||||
exports.create_named_method("getEnvVariable", get_env_variable)?;
|
||||
exports.create_named_method("throwSyntaxError", throw_syntax_error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue