napi-rs/test_module/src/error.rs

34 lines
971 B
Rust
Raw Normal View History

use napi::{CallContext, Error, JsBoolean, JsString, JsUnknown, Module, Result, Status};
#[js_function]
fn test_throw(_ctx: CallContext) -> Result<JsUnknown> {
Err(Error::from_status(Status::GenericFailure))
}
#[js_function(1)]
fn test_throw_with_reason(ctx: CallContext) -> Result<JsUnknown> {
let reason = ctx.get::<JsString>(0)?;
Err(Error::new(
Status::GenericFailure,
2020-09-28 01:27:37 +09:00
reason.into_utf8()?.as_str()?.to_owned(),
))
}
#[js_function]
pub fn test_throw_with_panic(_ctx: CallContext) -> Result<JsUnknown> {
panic!("don't panic.");
}
#[js_function(1)]
pub fn is_error(ctx: CallContext) -> Result<JsBoolean> {
let js_value = ctx.get::<JsUnknown>(0)?;
ctx.env.get_boolean(js_value.is_error()?)
}
pub fn register_js(module: &mut Module) -> Result<()> {
module.create_named_method("testThrow", test_throw)?;
module.create_named_method("testThrowWithReason", test_throw_with_reason)?;
module.create_named_method("isError", is_error)?;
Ok(())
}