feat(node): surface Rust errors as typed JavaScript errors (#4901)

## Summary
The Node SDK now throws typed `LanceError` subclasses instead of one
generic `Error` with an indented `Caused by` string.

Fixes #222

## Before / after
```ts
try {
  await db.openTable(\"missing\");
} catch (error) {
  if (error instanceof TableNotFoundError) {
    error.code;       // \"TableNotFound\"
    error.tableName;  // \"missing\"
    error.message;    // \"Table 'missing' was not found\"
    error.cause;      // underlying dataset error
  }
}
```

## Changes
- `nodejs/src/error.rs` — map each `lancedb::Error` variant to a
one-line header + `error.cause`
- `nodejs/src/query.rs`, `nodejs/src/merge.rs` — pass errors through
instead of stringifying
- `nodejs/lancedb/errors.ts`, `errors_install.ts` — real subclasses when
the package loads
- Tests + generated API docs under `docs/src/js/`

## Test plan
- [x] Native debug build, `tsc`, Biome, `cargo clippy -p lancedb-nodejs`
- [x] Jest: new error tests, remote retry, connection/query/table (594
passed)

## Notes
Node-API cannot construct a custom `Error` subclass from an async Rust
rejection, so translation happens in JS when `@lancedb/lancedb` loads.
Calling the raw native addon without that entrypoint still shows the
header line.

---------

Signed-off-by: ZYZ666-RGB <1991039819@qq.com>
Signed-off-by: yuzhou <1991039819@qq.com>
Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
yuzhou
2026-12-01 11:28:22 +08:00
committed by GitHub
co-authored by Xuanwo
parent 071c220713
commit b3ad97a28d
49 changed files with 16626 additions and 96 deletions
+312 -20
View File
@@ -1,40 +1,332 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
//! Translate [`lancedb::Error`] into the [`napi::Error`] values Node receives.
//!
//! Async Node-API rejections can carry a message, a Node-API status code, and
//! `error.cause`. They cannot carry an application error subclass. Each LanceDB
//! error is therefore encoded as a single-line `LanceError {json}` header
//! followed by the Rust [`Display`] text. `lancedb/errors.ts` reads that header
//! once, on the way out of the native module, and rethrows a real subclass.
//! Nested Rust sources become `error.cause` instead of indented `"Caused by"`
//! text.
use std::error::Error as StdError;
use lancedb::error::Error as LanceError;
use serde_json::{Map, Value, json};
pub type Result<T> = napi::Result<T>;
const HEADER_PREFIX: &str = "LanceError ";
const MAX_CAUSE_DEPTH: usize = 8;
pub trait NapiErrorExt<T> {
/// Convert to a napi error using from_reason(err.to_string())
/// Convert a LanceDB error into a Node error, preserving its kind and cause chain.
fn default_error(self) -> Result<T>;
}
impl<T> NapiErrorExt<T> for std::result::Result<T, lancedb::Error> {
impl<T> NapiErrorExt<T> for std::result::Result<T, LanceError> {
fn default_error(self) -> Result<T> {
self.map_err(|err| convert_error(&err))
}
}
pub fn convert_error(err: &dyn std::error::Error) -> napi::Error {
let mut message = err.to_string();
pub fn convert_error(err: &(dyn StdError + 'static)) -> napi::Error {
convert_error_at(err, 0)
}
// Append causes
let mut cause = err.source();
let mut indent = 2;
while let Some(err) = cause {
let cause_message = format!("Caused by: {}", err);
message.push_str(&indent_string(&cause_message, indent));
fn convert_error_at(err: &(dyn StdError + 'static), depth: usize) -> napi::Error {
let mut napi_err = napi::Error::from_reason(format_message(err));
if depth < MAX_CAUSE_DEPTH
&& let Some(source) = error_cause(err)
{
napi_err.set_cause(convert_error_at(source, depth + 1));
}
napi_err
}
cause = err.source();
indent += 2;
/// The next error in the chain. `JobFailed` keeps its underlying error, such as
/// the `Sql` error of a failed isolated Flight SQL job, in `failure.source`
/// rather than in [`StdError::source`].
fn error_cause<'a>(err: &'a (dyn StdError + 'static)) -> Option<&'a (dyn StdError + 'static)> {
if let Some(LanceError::JobFailed { failure, .. }) = err.downcast_ref::<LanceError>()
&& let Some(source) = failure.source.as_deref()
{
return Some(source);
}
err.source()
}
fn format_message(err: &(dyn StdError + 'static)) -> String {
match err.downcast_ref::<LanceError>() {
Some(err) => format!("{HEADER_PREFIX}{}\n{err}", error_payload(err)),
None => err.to_string(),
}
}
fn error_payload(err: &LanceError) -> String {
let mut meta = Map::new();
let code = error_code(err);
meta.insert("code".to_owned(), Value::String(code.to_owned()));
insert_fields(err, &mut meta);
Value::Object(meta).to_string()
}
fn error_code(err: &LanceError) -> &'static str {
match err {
LanceError::InvalidTableName { .. } => "InvalidTableName",
LanceError::InvalidInput { .. } => "InvalidInput",
LanceError::TableNotFound { .. } => "TableNotFound",
LanceError::TableCorrupted { .. } => "TableCorrupted",
LanceError::DatabaseNotFound { .. } => "DatabaseNotFound",
LanceError::DatabaseAlreadyExists { .. } => "DatabaseAlreadyExists",
LanceError::IndexNotFound { .. } => "IndexNotFound",
LanceError::EmbeddingFunctionNotFound { .. } => "EmbeddingFunctionNotFound",
LanceError::ColumnNotFound { .. } => "ColumnNotFound",
LanceError::FieldNotFound { .. } => "FieldNotFound",
LanceError::ColumnAlreadyExists { .. } => "ColumnAlreadyExists",
LanceError::NotAComputedColumn { .. } => "NotAComputedColumn",
LanceError::NotAMaterializedView { .. } => "NotAMaterializedView",
LanceError::InvalidExpression { .. } => "InvalidExpression",
LanceError::TableAlreadyExists { .. } => "TableAlreadyExists",
LanceError::CreateDir { .. } => "CreateDir",
LanceError::Schema { .. } => "Schema",
#[cfg(feature = "remote")]
LanceError::Sql { .. } => "Sql",
LanceError::Runtime { .. } => "Runtime",
LanceError::Timeout { .. } => "Timeout",
LanceError::JobFailed { .. } => "JobFailed",
LanceError::JobCancelled { .. } => "JobCancelled",
LanceError::JobNotFound { .. } => "JobNotFound",
LanceError::ObjectStore { .. } => "ObjectStore",
LanceError::Lance { .. } => "Lance",
#[cfg(feature = "remote")]
LanceError::Http { .. } => "Http",
#[cfg(feature = "remote")]
LanceError::Retry { .. } => "Retry",
#[cfg(feature = "remote")]
LanceError::ResponseInterrupted { .. } => "ResponseInterrupted",
LanceError::Arrow { .. } => "Arrow",
LanceError::NotSupported { .. } => "NotSupported",
LanceError::External { .. } => "External",
LanceError::Other { .. } => "Other",
}
}
fn insert_fields(err: &LanceError, meta: &mut Map<String, Value>) {
match err {
LanceError::InvalidTableName { name, .. } | LanceError::TableAlreadyExists { name } => {
meta.insert("tableName".to_owned(), json!(name));
}
LanceError::TableNotFound { name, .. } | LanceError::TableCorrupted { name, .. } => {
meta.insert("tableName".to_owned(), json!(name));
#[cfg(feature = "remote")]
insert_remote_metadata(err, meta);
}
LanceError::DatabaseNotFound { name } | LanceError::DatabaseAlreadyExists { name } => {
meta.insert("databaseName".to_owned(), json!(name));
}
LanceError::IndexNotFound { name } => {
meta.insert("indexName".to_owned(), json!(name));
}
LanceError::EmbeddingFunctionNotFound { name, .. } => {
meta.insert("functionName".to_owned(), json!(name));
}
LanceError::ColumnNotFound { name }
| LanceError::ColumnAlreadyExists { name }
| LanceError::NotAComputedColumn { name }
| LanceError::FieldNotFound { name, .. } => {
meta.insert("columnName".to_owned(), json!(name));
}
LanceError::NotAMaterializedView { name } => {
meta.insert("tableName".to_owned(), json!(name));
}
LanceError::InvalidExpression { column, .. } => {
meta.insert("columnName".to_owned(), json!(column));
}
LanceError::CreateDir { path, .. } => {
meta.insert("path".to_owned(), json!(path));
}
LanceError::JobFailed { job_id, failure } => {
insert_optional(meta, "jobId", job_id.as_deref());
insert_optional(meta, "phase", failure.phase.as_deref());
if let Some(retryable) = failure.retryable {
meta.insert("retryable".to_owned(), json!(retryable));
}
insert_optional(meta, "sqlJobId", failure.sql_job_id.as_deref());
#[cfg(feature = "remote")]
insert_remote_metadata(err, meta);
}
LanceError::JobCancelled { job_id } => {
insert_optional(meta, "jobId", job_id.as_deref());
}
LanceError::JobNotFound { job_id, .. } => {
meta.insert("jobId".to_owned(), json!(job_id));
#[cfg(feature = "remote")]
insert_remote_metadata(err, meta);
}
#[cfg(feature = "remote")]
LanceError::ResponseInterrupted { request_id, .. } => {
meta.insert("requestId".to_owned(), json!(request_id));
}
#[cfg(feature = "remote")]
LanceError::Http {
request_id,
status_code,
..
} => {
meta.insert("requestId".to_owned(), json!(request_id));
if let Some(status_code) = status_code {
meta.insert("statusCode".to_owned(), json!(status_code.as_u16()));
}
insert_remote_metadata(err, meta);
}
#[cfg(feature = "remote")]
LanceError::Retry {
request_id,
status_code,
request_failures,
max_request_failures,
connect_failures,
max_connect_failures,
read_failures,
max_read_failures,
..
} => {
meta.insert("requestId".to_owned(), json!(request_id));
if let Some(status_code) = status_code {
meta.insert("statusCode".to_owned(), json!(status_code.as_u16()));
}
meta.insert("requestFailures".to_owned(), json!(request_failures));
meta.insert("maxRequestFailures".to_owned(), json!(max_request_failures));
meta.insert("connectFailures".to_owned(), json!(connect_failures));
meta.insert("maxConnectFailures".to_owned(), json!(max_connect_failures));
meta.insert("readFailures".to_owned(), json!(read_failures));
meta.insert("maxReadFailures".to_owned(), json!(max_read_failures));
insert_remote_metadata(err, meta);
}
#[cfg(feature = "remote")]
LanceError::Sql {
request_id,
grpc_code,
..
} => {
meta.insert("requestId".to_owned(), json!(request_id));
meta.insert("grpcCode".to_owned(), json!(grpc_code));
insert_remote_metadata(err, meta);
}
_ => {}
}
}
fn insert_optional(meta: &mut Map<String, Value>, key: &str, value: Option<&str>) {
if let Some(value) = value {
meta.insert(key.to_owned(), json!(value));
}
}
#[cfg(feature = "remote")]
fn insert_remote_metadata(err: &LanceError, meta: &mut Map<String, Value>) {
if let Some(details) = err.http_error_details() {
meta.insert("errorCode".to_owned(), json!(details.error_code));
meta.insert("resourceKind".to_owned(), json!(details.resource_kind));
meta.insert("resourceName".to_owned(), json!(details.resource_name));
meta.insert("namespacePath".to_owned(), json!(details.namespace_path));
}
let Some(metadata) = err.remote_error_metadata() else {
return;
};
if let Some(error_code) = metadata.error_code.as_deref() {
meta.entry("errorCode".to_owned())
.or_insert(json!(error_code));
}
if let Some(job_id) = metadata.job_id.as_deref() {
meta.entry("jobId".to_owned()).or_insert(json!(job_id));
}
if let Some(job_request_id) = metadata.job_request_id.as_deref() {
meta.insert("jobRequestId".to_owned(), json!(job_request_id));
}
// `x-lancedb-resource` identity; structured body details take precedence.
if let Some(resource) = metadata.resource.as_ref() {
meta.entry("resourceKind".to_owned())
.or_insert(json!(resource.kind));
meta.entry("resourceName".to_owned())
.or_insert(json!(resource.name));
meta.entry("namespacePath".to_owned())
.or_insert(json!(resource.namespace_path));
}
}
#[cfg(all(test, feature = "remote"))]
mod tests {
use std::sync::Arc;
use lancedb::error::{JobFailure, RemoteErrorMetadata, RemoteResourceIdentity};
use super::*;
fn header(err: &napi::Error) -> Value {
let line = err.reason.lines().next().unwrap();
serde_json::from_str(line.strip_prefix(HEADER_PREFIX).unwrap()).unwrap()
}
napi::Error::from_reason(message)
}
fn sql_error(resource: Option<RemoteResourceIdentity>) -> LanceError {
let mut metadata = RemoteErrorMetadata::default();
metadata.job_id = Some("sql-job".into());
metadata.resource = resource;
LanceError::Sql {
message: "table 'docs' was not found".into(),
request_id: "worker-request".into(),
grpc_code: 5,
metadata: Box::new(metadata),
}
}
fn indent_string(s: &str, amount: usize) -> String {
let indent = " ".repeat(amount);
s.lines()
.map(|line| format!("{}{}", indent, line))
.collect::<Vec<_>>()
.join("\n")
#[test]
fn job_failed_keeps_its_failure_source_as_cause() {
let err = LanceError::JobFailed {
job_id: Some("sql-job".into()),
failure: Box::new(JobFailure {
sql_job_id: Some("sql-job".into()),
source: Some(Arc::new(sql_error(None))),
..Default::default()
}),
};
let converted = convert_error(&err);
assert_eq!(header(&converted)["code"], "JobFailed");
let cause = converted.cause.as_deref().expect("JobFailed cause");
let cause_header = header(cause);
assert_eq!(cause_header["code"], "Sql");
assert_eq!(cause_header["requestId"], "worker-request");
assert_eq!(cause_header["grpcCode"], 5);
assert!(
cause
.reason
.ends_with("table 'docs' was not found (request_id=worker-request)")
);
}
#[test]
fn resource_header_populates_resource_fields() {
let resource = RemoteResourceIdentity::new("table", "docs", vec!["ns".into()]);
let converted = convert_error(&sql_error(Some(resource)));
let header = header(&converted);
assert_eq!(header["code"], "Sql");
assert_eq!(header["resourceKind"], "table");
assert_eq!(header["resourceName"], "docs");
assert_eq!(header["namespacePath"], json!(["ns"]));
}
#[test]
fn absent_resource_header_leaves_resource_fields_unset() {
let header = header(&convert_error(&sql_error(None)));
assert!(header.get("resourceKind").is_none());
assert!(header.get("resourceName").is_none());
assert!(header.get("namespacePath").is_none());
}
}
+6 -9
View File
@@ -66,9 +66,7 @@ impl NativeMergeInsertBuilder {
#[napi(catch_unwind)]
pub async fn execute(&self, buf: Buffer, retries: Option<u32>) -> napi::Result<MergeResult> {
let data = ipc_file_to_batches(buf.to_vec()).map_err(|e| {
napi::Error::from_reason(format!("Failed to read IPC file: {}", convert_error(&e)))
})?;
let data = ipc_file_to_batches(buf.to_vec()).map_err(|e| convert_error(&e))?;
let mut this = self.clone();
if let Some(retries) = retries {
@@ -77,12 +75,11 @@ impl NativeMergeInsertBuilder {
this.inner.retries(retries);
}
let res = this.inner.execute(data).await.map_err(|e| {
napi::Error::from_reason(format!(
"Failed to execute merge insert: {}",
convert_error(&e)
))
})?;
let res = this
.inner
.execute(data)
.await
.map_err(|e| convert_error(&e))?;
Ok(res.into())
}
}
+18 -54
View File
@@ -214,23 +214,16 @@ impl Query {
let inner_stream = query
.execute_with_options(execution_opts)
.await
.map_err(|e| {
napi::Error::from_reason(format!(
"Failed to execute query stream: {}",
convert_error(&e)
))
})?;
.map_err(|e| convert_error(&e))?;
Ok(RecordBatchIterator::new(inner_stream))
}
#[napi]
pub async fn explain_plan(&self, verbose: bool) -> napi::Result<String> {
self.inner.explain_plan(verbose).await.map_err(|e| {
napi::Error::from_reason(format!(
"Failed to retrieve the query plan: {}",
convert_error(&e)
))
})
self.inner
.explain_plan(verbose)
.await
.map_err(|e| convert_error(&e))
}
#[napi(catch_unwind)]
@@ -239,12 +232,7 @@ impl Query {
self.inner
.analyze_plan_with_options(options)
.await
.map_err(|e| {
napi::Error::from_reason(format!(
"Failed to execute analyze plan: {}",
convert_error(&e)
))
})
.map_err(|e| convert_error(&e))
}
}
@@ -462,23 +450,16 @@ impl VectorQuery {
let inner_stream = query
.execute_with_options(execution_opts)
.await
.map_err(|e| {
napi::Error::from_reason(format!(
"Failed to execute query stream: {}",
convert_error(&e)
))
})?;
.map_err(|e| convert_error(&e))?;
Ok(RecordBatchIterator::new(inner_stream))
}
#[napi]
pub async fn explain_plan(&self, verbose: bool) -> napi::Result<String> {
self.inner.explain_plan(verbose).await.map_err(|e| {
napi::Error::from_reason(format!(
"Failed to retrieve the query plan: {}",
convert_error(&e)
))
})
self.inner
.explain_plan(verbose)
.await
.map_err(|e| convert_error(&e))
}
#[napi(catch_unwind)]
@@ -487,12 +468,7 @@ impl VectorQuery {
self.inner
.analyze_plan_with_options(options)
.await
.map_err(|e| {
napi::Error::from_reason(format!(
"Failed to execute analyze plan: {}",
convert_error(&e)
))
})
.map_err(|e| convert_error(&e))
}
}
@@ -555,23 +531,16 @@ impl TakeQuery {
let inner_stream = query
.execute_with_options(execution_opts)
.await
.map_err(|e| {
napi::Error::from_reason(format!(
"Failed to execute query stream: {}",
convert_error(&e)
))
})?;
.map_err(|e| convert_error(&e))?;
Ok(RecordBatchIterator::new(inner_stream))
}
#[napi]
pub async fn explain_plan(&self, verbose: bool) -> napi::Result<String> {
self.inner.explain_plan(verbose).await.map_err(|e| {
napi::Error::from_reason(format!(
"Failed to retrieve the query plan: {}",
convert_error(&e)
))
})
self.inner
.explain_plan(verbose)
.await
.map_err(|e| convert_error(&e))
}
#[napi(catch_unwind)]
@@ -580,12 +549,7 @@ impl TakeQuery {
self.inner
.analyze_plan_with_options(options)
.await
.map_err(|e| {
napi::Error::from_reason(format!(
"Failed to execute analyze plan: {}",
convert_error(&e)
))
})
.map_err(|e| convert_error(&e))
}
}