From 13996c1864d3048a8c9a27aee7088163f9b4af31 Mon Sep 17 00:00:00 2001 From: iuser Date: Sun, 14 Aug 2022 08:03:31 +0800 Subject: [PATCH] feat(napi): error_anyhow feature --- Cargo.toml | 1 + crates/napi/Cargo.toml | 5 +++++ crates/napi/src/error.rs | 14 ++++++++++++++ crates/napi/src/lib.rs | 3 +++ 4 files changed, 23 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index a6fc619d..1b6d31f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,5 @@ [workspace] +resolver = "2" members = [ "./crates/backend", "./crates/build", diff --git a/crates/napi/Cargo.toml b/crates/napi/Cargo.toml index d954013c..f45d4694 100644 --- a/crates/napi/Cargo.toml +++ b/crates/napi/Cargo.toml @@ -24,6 +24,7 @@ experimental = ["napi-sys/experimental"] chrono_date = ["chrono", "napi5"] full = ["latin1", "napi8", "async", "serde-json", "experimental", "chrono_date"] latin1 = ["encoding_rs"] +error_anyhow = ["anyhow"] napi1 = [] napi2 = ["napi1"] napi3 = ["napi2", "napi-sys/napi3"] @@ -53,6 +54,10 @@ once_cell = "1" thread_local = "1" bitflags = "1" +[dependencies.anyhow] +version = "1" +optional = true + [dependencies.napi-sys] version = "2.2.2" path = "../sys" diff --git a/crates/napi/src/error.rs b/crates/napi/src/error.rs index ec368b0a..d6d9e837 100644 --- a/crates/napi/src/error.rs +++ b/crates/napi/src/error.rs @@ -72,6 +72,13 @@ impl From for Error { } } +#[cfg(feature = "anyhow")] +impl From for Error { + fn from(value: anyhow::Error) -> Self { + Error::new(Status::GenericFailure, format!("{}", value)) + } +} + impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if !self.reason.is_empty() { @@ -160,6 +167,13 @@ impl TryFrom for ExtendedErrorInfo { pub struct JsError(Error); +#[cfg(feature = "anyhow")] +impl From for JsError { + fn from(value: anyhow::Error) -> Self { + JsError(Error::new(Status::GenericFailure, value.to_string())) + } +} + pub struct JsTypeError(Error); pub struct JsRangeError(Error); diff --git a/crates/napi/src/lib.rs b/crates/napi/src/lib.rs index 7892567b..642d5040 100644 --- a/crates/napi/src/lib.rs +++ b/crates/napi/src/lib.rs @@ -217,3 +217,6 @@ pub mod __private { #[cfg(feature = "tokio_rt")] pub extern crate tokio; + +#[cfg(feature = "error_anyhow")] +pub extern crate anyhow;