From 2265ca3e1a3d747ec3309a4f8cd780feb7988100 Mon Sep 17 00:00:00 2001 From: Jade-fu <32590310+richerfu@users.noreply.github.com> Date: Thu, 4 Jul 2024 14:47:32 +0800 Subject: [PATCH] fix(napi): asynchronous functions can return any errors (#2165) * feat(napi): asynchronous functions can return any errors as long as they implement the Into trait. * chore: use impl Into --- crates/backend/src/codegen/fn.rs | 7 ++++++- crates/napi/src/tokio_runtime.rs | 4 ++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/backend/src/codegen/fn.rs b/crates/backend/src/codegen/fn.rs index 504ca105..a9ba8e77 100644 --- a/crates/backend/src/codegen/fn.rs +++ b/crates/backend/src/codegen/fn.rs @@ -103,7 +103,12 @@ impl TryToTokens for NapiFn { let call = if self.is_ret_result { quote! { #receiver(#(#arg_names),*).await } } else { - quote! { Ok(#receiver(#(#arg_names),*).await) } + let ret_type = if let Some(t) = &self.ret { + quote! { #t } + } else { + quote! { () } + }; + quote! { Ok(#receiver(#(#arg_names),*).await) as napi::bindgen_prelude::Result<#ret_type> } }; quote! { napi::bindgen_prelude::execute_tokio_future(env, async move { #call }, move |env, #receiver_ret_name| { diff --git a/crates/napi/src/tokio_runtime.rs b/crates/napi/src/tokio_runtime.rs index b5437781..038addbe 100644 --- a/crates/napi/src/tokio_runtime.rs +++ b/crates/napi/src/tokio_runtime.rs @@ -150,7 +150,7 @@ impl Result>, + Fut: 'static + Send + Future>>, Resolver: 'static + FnOnce(sys::napi_env, Data) -> Result, >( env: sys::napi_env, @@ -169,7 +169,7 @@ pub fn execute_tokio_future< .resolve(env.raw(), v) .map(|v| unsafe { JsUnknown::from_raw_unchecked(env.raw(), v) }) }), - Err(e) => deferred.reject(e), + Err(e) => deferred.reject(e.into()), } };