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
+386
View File
@@ -0,0 +1,386 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import * as vm from "node:vm";
import * as tmp from "tmp";
import {
ColumnNotFoundError,
FieldNotFoundError,
HttpError,
InvalidInputError,
InvalidTableNameError,
JobFailedError,
LanceError,
SqlError,
TableAlreadyExistsError,
TableNotFoundError,
connect,
isAlreadyExistsError,
isLanceError,
} from "../lancedb";
import { LANCE_ERROR_MARK, materializeLanceError } from "../lancedb/errors";
type LanceDbModule = typeof import("../lancedb");
type ErrorsModule = typeof import("../lancedb/errors");
describe("materializeLanceError", () => {
it("rebuilds a native header as a typed error and keeps the cause chain", () => {
const cause = new Error(
'LanceError {"code":"Http","requestId":"req-1","statusCode":404}\nHttp error: (request_id=req-1) missing',
);
const raw = new Error(
'LanceError {"code":"TableNotFound","tableName":"missing"}\nTable \'missing\' was not found',
);
raw.cause = cause;
const error = materializeLanceError(raw);
expect(error).toBeInstanceOf(TableNotFoundError);
expect(error).toBeInstanceOf(LanceError);
expect(error).toBeInstanceOf(Error);
if (!(error instanceof TableNotFoundError)) {
throw error;
}
expect(error.code).toBe("TableNotFound");
expect(error.name).toBe("TableNotFoundError");
expect(error.message).toBe("Table 'missing' was not found");
expect(error.message).not.toContain("Caused by:");
expect(error.message).not.toContain("LanceError");
expect(error.tableName).toBe("missing");
expect(error.cause).toBeInstanceOf(HttpError);
if (!(error.cause instanceof HttpError)) {
throw error.cause;
}
expect(error.cause.code).toBe("Http");
expect(error.cause.requestId).toBe("req-1");
expect(error.cause.statusCode).toBe(404);
expect(error.cause.message).toBe("Http error: (request_id=req-1) missing");
expect(error.stack).toContain(
"TableNotFoundError: Table 'missing' was not found",
);
});
it("keeps the SQL error of a failed isolated job as its cause", () => {
const raw = new Error(
'LanceError {"code":"JobFailed","jobId":"sql-job","sqlJobId":"sql-job"}\nJob sql-job failed',
);
raw.cause = new Error(
'LanceError {"code":"Sql","requestId":"worker-request","grpcCode":5}\nmissing (request_id=worker-request)',
);
const error = materializeLanceError(raw);
expect(error).toBeInstanceOf(JobFailedError);
if (!(error instanceof JobFailedError)) {
throw error;
}
expect(error.cause).toBeInstanceOf(SqlError);
if (!(error.cause instanceof SqlError)) {
throw error.cause;
}
expect(error.cause.requestId).toBe("worker-request");
expect(error.cause.grpcCode).toBe(5);
});
it("maps field misses onto ColumnNotFoundError and preserves the specific code", () => {
const error = materializeLanceError(
new Error(
'LanceError {"code":"FieldNotFound","columnName":"vector"}\nNo field named vector',
),
);
expect(error).toBeInstanceOf(FieldNotFoundError);
expect(error).toBeInstanceOf(ColumnNotFoundError);
if (!(error instanceof FieldNotFoundError)) {
throw error;
}
expect(error.code).toBe("FieldNotFound");
expect(error.columnName).toBe("vector");
});
it("keeps an unknown Rust kind as LanceError with that code", () => {
const error = materializeLanceError(
new Error('LanceError {"code":"FutureKind"}\nnot classified yet'),
);
expect(error).toBeInstanceOf(LanceError);
expect(error).not.toBeInstanceOf(TableNotFoundError);
if (!(error instanceof LanceError)) {
throw error;
}
expect(error.code).toBe("FutureKind");
expect(error.message).toBe("not classified yet");
});
it("leaves TypeScript errors that are not from Rust untouched", () => {
const error = new Error("Table some_table is closed");
expect(materializeLanceError(error)).toBe(error);
expect(isLanceError(error)).toBe(false);
});
it("rebuilds an error already translated by another module realm", () => {
const cause = foreignLanceError({
name: "HttpError",
code: "Http",
message: "Http error: (request_id=req-1) missing",
requestId: "req-1",
statusCode: 404,
});
const foreign = foreignLanceError({
name: "TableNotFoundError",
code: "TableNotFound",
message: "Table 'missing' was not found",
tableName: "missing",
cause,
});
const error = materializeLanceError(foreign);
expect(error).toBeInstanceOf(TableNotFoundError);
expect(error).not.toBe(foreign);
if (!(error instanceof TableNotFoundError)) {
throw error;
}
expect(error.code).toBe("TableNotFound");
expect(error.tableName).toBe("missing");
expect(error.message).toBe("Table 'missing' was not found");
expect(error.message).not.toContain("LanceError {");
expect(error.cause).toBeInstanceOf(HttpError);
if (!(error.cause instanceof HttpError)) {
throw error.cause;
}
expect(error.cause.code).toBe("Http");
expect(error.cause.requestId).toBe("req-1");
expect(error.cause.statusCode).toBe(404);
expect(error.cause.message).toBe("Http error: (request_id=req-1) missing");
});
it("does not treat an unmarked foreign error as a LanceError", () => {
const foreign = vm.runInNewContext(
`(() => {
const error = new Error("Table 'missing' was not found");
error.code = "TableNotFound";
error.tableName = "missing";
return error;
})()`,
);
const error = materializeLanceError(foreign);
expect(error).not.toBeInstanceOf(LanceError);
expect(error).not.toBeInstanceOf(TableNotFoundError);
});
it("treats invalid table names as invalid input", () => {
const error = new InvalidTableNameError("bad name");
expect(error).toBeInstanceOf(InvalidInputError);
expect(error.code).toBe("InvalidTableName");
expect(isLanceError(error)).toBe(true);
expect(isAlreadyExistsError(error)).toBe(false);
});
});
describe("native LanceDB errors", () => {
let tmpDir: tmp.DirResult;
beforeEach(() => {
tmpDir = tmp.dirSync({ unsafeCleanup: true });
});
afterEach(() => {
tmpDir.removeCallback();
});
it("throws TableNotFoundError when opening a missing table", async () => {
const db = await connect(tmpDir.name);
await expect(db.openTable("missing")).rejects.toBeInstanceOf(
TableNotFoundError,
);
try {
await db.openTable("missing");
throw new Error("expected openTable to fail");
} catch (error) {
expect(isLanceError(error)).toBe(true);
if (!(error instanceof TableNotFoundError)) {
throw error;
}
expect(error.code).toBe("TableNotFound");
expect(error.tableName).toBe("missing");
expect(error.message).toContain("missing");
expect(error.message).not.toContain("LanceError {");
expect(error.message).not.toContain("Caused by:");
}
});
it("throws TableAlreadyExistsError when creating a table twice", async () => {
const db = await connect(tmpDir.name);
await db.createTable("docs", [{ id: 1 }]);
await expect(db.createTable("docs", [{ id: 2 }])).rejects.toBeInstanceOf(
TableAlreadyExistsError,
);
try {
await db.createTable("docs", [{ id: 3 }]);
throw new Error("expected createTable to fail");
} catch (error) {
expect(isAlreadyExistsError(error)).toBe(true);
if (!(error instanceof TableAlreadyExistsError)) {
throw error;
}
expect(error.code).toBe("TableAlreadyExists");
expect(error.tableName).toBe("docs");
expect(error.message).toContain("already exists");
}
});
it("throws ColumnNotFoundError when a filter names a missing column", async () => {
const db = await connect(tmpDir.name);
const table = await db.createTable("docs", [{ id: 1, vector: [0.1, 0.2] }]);
await expect(
table.query().where("missing > 1").toArray(),
).rejects.toBeInstanceOf(ColumnNotFoundError);
});
it("keeps each SDK load's subclasses after another load has translated an error", async () => {
const firstDir = tmp.dirSync({ unsafeCleanup: true });
const secondDir = tmp.dirSync({ unsafeCleanup: true });
try {
let openMissing!: () => Promise<TableNotFoundError>;
let firstTableNotFound!: LanceDbModule["TableNotFoundError"];
jest.isolateModules(() => {
const lancedb = require("../lancedb") as LanceDbModule;
firstTableNotFound = lancedb.TableNotFoundError;
openMissing = async () => {
const db = await lancedb.connect(firstDir.name);
try {
await db.openTable("missing");
throw new Error("expected openTable to fail");
} catch (error) {
expect(error).toBeInstanceOf(lancedb.TableNotFoundError);
if (!(error instanceof lancedb.TableNotFoundError)) {
throw error;
}
expect(error.code).toBe("TableNotFound");
expect(error.tableName).toBe("missing");
expect(error.message).not.toContain("LanceError {");
expect(error.message).not.toContain("Caused by:");
return error;
}
};
});
const firstError = await openMissing();
let checkLaterLoad!: (previous: unknown) => Promise<void>;
let laterTableNotFound!: LanceDbModule["TableNotFoundError"];
jest.isolateModules(() => {
const lancedb = require("../lancedb") as LanceDbModule;
laterTableNotFound = lancedb.TableNotFoundError;
const { materializeLanceError: materialize } =
require("../lancedb/errors") as ErrorsModule;
checkLaterLoad = async (previous: unknown) => {
const rebuilt = materialize(previous);
expect(rebuilt).toBeInstanceOf(lancedb.TableNotFoundError);
expect(rebuilt).not.toBe(previous);
if (!(rebuilt instanceof lancedb.TableNotFoundError)) {
throw rebuilt;
}
expect(rebuilt.code).toBe("TableNotFound");
expect(rebuilt.tableName).toBe("missing");
expect(rebuilt.message).toBe(firstError.message);
const db = await lancedb.connect(secondDir.name);
try {
await db.openTable("missing");
throw new Error("expected openTable to fail");
} catch (error) {
expect(error).toBeInstanceOf(lancedb.TableNotFoundError);
if (!(error instanceof lancedb.TableNotFoundError)) {
throw error;
}
expect(error.code).toBe("TableNotFound");
expect(error.tableName).toBe("missing");
expect(error.message).not.toContain("LanceError {");
}
await db.createTable("docs", [{ id: 1 }]);
try {
await db.createTable("docs", [{ id: 2 }]);
throw new Error("expected createTable to fail");
} catch (error) {
expect(error).toBeInstanceOf(lancedb.TableAlreadyExistsError);
if (!(error instanceof lancedb.TableAlreadyExistsError)) {
throw error;
}
expect(error.code).toBe("TableAlreadyExists");
expect(error.tableName).toBe("docs");
}
const table = await db.openTable("docs");
try {
await table.query().where("missing > 1").toArray();
throw new Error("expected query to fail");
} catch (error) {
expect(error).toBeInstanceOf(lancedb.LanceError);
expect(error).toBeInstanceOf(lancedb.ColumnNotFoundError);
if (!(error instanceof lancedb.ColumnNotFoundError)) {
throw error;
}
expect(error.message).not.toContain("LanceError {");
}
};
});
await checkLaterLoad(firstError);
const stillFirst = await openMissing();
expect(stillFirst).toBeInstanceOf(firstTableNotFound);
expect(stillFirst.tableName).toBe("missing");
expect(stillFirst).not.toBeInstanceOf(laterTableNotFound);
expect(stillFirst).not.toBeInstanceOf(TableNotFoundError);
} finally {
firstDir.removeCallback();
secondDir.removeCallback();
}
});
});
function foreignLanceError(fields: {
name: string;
code: string;
message: string;
cause?: unknown;
requestId?: string;
statusCode?: number;
tableName?: string;
}): Error {
return vm.runInNewContext(
`(() => {
class ForeignError extends Error {
constructor(message, cause) {
super(message, { cause });
this.name = name;
this.code = code;
if (requestId !== undefined) this.requestId = requestId;
if (statusCode !== undefined) this.statusCode = statusCode;
if (tableName !== undefined) this.tableName = tableName;
Object.defineProperty(this, mark, { value: true });
}
}
return new ForeignError(message, cause);
})()`,
{
name: fields.name,
code: fields.code,
message: fields.message,
cause: fields.cause,
requestId: fields.requestId,
statusCode: fields.statusCode,
tableName: fields.tableName,
mark: LANCE_ERROR_MARK,
},
) as Error;
}
+20 -2
View File
@@ -6,7 +6,12 @@ import * as http from "http";
import { execFileSync } from "node:child_process";
import * as os from "os";
import * as path from "path";
import { OAuthConfig, OAuthFlowType, OAuthSession } from "../lancedb/oauth";
import {
InvalidInputError,
OAuthConfig,
OAuthFlowType,
OAuthSession,
} from "../lancedb";
function tempCacheDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), "lancedb-oauth-cache-"));
@@ -60,7 +65,20 @@ describe("OAuthSession", () => {
scopes: ["openid"],
flow: OAuthFlowType.DeviceCode,
};
expect(() => new OAuthSession(config)).toThrow(/token/);
let thrown: unknown;
try {
new OAuthSession(config);
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(InvalidInputError);
if (!(thrown instanceof InvalidInputError)) {
throw thrown;
}
expect(thrown.code).toBe("InvalidInput");
expect(thrown.message).toBe(
"Invalid input, OAuthSession requires OAuthConfig.token_cache to be set",
);
});
it("rejects azure managed identity persistence", () => {
+44 -4
View File
@@ -10,8 +10,10 @@ import {
ClientConfig,
Connection,
ConnectionOptions,
HttpError,
OAuthConfig,
OAuthFlowType,
RetryError,
TlsConfig,
blob,
connect,
@@ -792,11 +794,21 @@ describe("remote connection", () => {
try {
await db.tableNames();
fail("expected an error");
// biome-ignore lint/suspicious/noExplicitAny: skip
} catch (e: any) {
} catch (e: unknown) {
expect(e).toBeInstanceOf(RetryError);
if (!(e instanceof RetryError)) {
throw e;
}
expect(e.code).toBe("Retry");
expect(e.message).toContain("Hit retry limit for request_id=");
expect(e.message).toContain("Caused by: Http error");
expect(e.message).toContain("500 Internal Server Error");
expect(e.message).not.toContain("Caused by:");
expect(e.requestId).toEqual(expect.any(String));
expect(e.cause).toBeInstanceOf(HttpError);
if (!(e.cause instanceof HttpError)) {
throw e.cause;
}
expect(e.cause.message).toContain("Http error");
expect(`${e.message}\n${e.cause.message}`).toContain("500");
}
},
{
@@ -807,6 +819,34 @@ describe("remote connection", () => {
);
});
it("reports resource identity supplied only by x-lancedb-resource", async () => {
const resource = Buffer.from(
// biome-ignore lint/style/useNamingConvention: Flight resource wire format
JSON.stringify({ kind: "table", name: "docs", namespace_path: ["ns"] }),
).toString("base64url");
await withMockDatabase(
(_req, res) => {
res
.writeHead(400, { "x-lancedb-resource": resource })
.end("bad request");
},
async (db) => {
const error = await db.tableNames().then(
() => undefined,
(e: unknown) => e,
);
expect(error).toBeInstanceOf(HttpError);
if (!(error instanceof HttpError)) {
throw error;
}
expect(error.statusCode).toBe(400);
expect(error.resourceKind).toBe("table");
expect(error.resourceName).toBe("docs");
expect(error.namespacePath).toEqual(["ns"]);
},
);
});
it("lists the rows a Function refresh skipped", async () => {
const bodies: unknown[] = [];
await withMockDatabase(
+2 -1
View File
@@ -16,6 +16,7 @@ import {
makeEmptyTable,
} from "./arrow";
import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry";
import { bindErrorTranslator } from "./errors";
import { Job } from "./job";
import { Listing, ListingOptions, validateListingOptions } from "./listing";
import {
@@ -631,7 +632,7 @@ export class LocalConnection extends Connection {
/** @hidden */
constructor(inner: LanceDbConnection) {
super();
this.inner = inner;
this.inner = bindErrorTranslator(inner);
}
isOpen(): boolean {
+810
View File
@@ -0,0 +1,810 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
/**
* Typed errors for the Node SDK.
*
* Rust errors used to arrive as one `Error` whose message was the Display text
* plus an indented `Caused by` chain. Native code now records the LanceDB error
* kind and its fields in a one-line header, and {@link installLanceErrorTranslation}
* turns that into one of the classes below before application code sees it.
*
* `error.code` is the Rust variant name (`"TableNotFound"`, `"Http"`, ...).
* `error.message` is that variant's own message, without the nested cause text.
* {@link LanceError} shows how to branch with `instanceof`.
*/
const HEADER = /^LanceError (\{.*\})(?:\n|$)/;
const MAX_CAUSE_DEPTH = 8;
/** Per-load marker so one SDK load does not wrap the same function twice. */
const WRAPPED = Symbol("lancedb.errorWrapped");
/**
* Points a wrapper at the native function it replaced. Shared across SDK loads
* so a later load wraps that function instead of stacking another wrapper.
*/
const ORIGINAL_FN = Symbol.for("lancedb.originalNativeFn");
/**
* WeakMap of native objects to the translator for the SDK load that owns them.
* Stored on the shared native constructor so every load sees the same map.
*/
const TRANSLATORS = Symbol.for("lancedb.errorTranslators");
type ErrorTranslator = (error: unknown) => unknown;
type TranslatorHost = {
[TRANSLATORS]?: WeakMap<object, ErrorTranslator>;
};
/**
* Marks a translated LanceDB error. A later SDK load cannot use `instanceof`
* against a class from an earlier load, but this symbol is shared by the
* process, so the later load can rebuild its own subclass.
*/
export const LANCE_ERROR_MARK = Symbol.for("lancedb.LanceError");
const METADATA_KEYS = [
"requestId",
"statusCode",
"errorCode",
"resourceKind",
"resourceName",
"namespacePath",
"tableName",
"columnName",
"databaseName",
"indexName",
"functionName",
"path",
"jobId",
"sqlJobId",
"jobRequestId",
"grpcCode",
"phase",
"retryable",
"requestFailures",
"maxRequestFailures",
"connectFailures",
"maxConnectFailures",
"readFailures",
"maxReadFailures",
] as const;
type AnyFn = (...args: unknown[]) => unknown;
export interface LanceErrorOptions extends ErrorOptions {
/** Rust variant name. Subclasses set this from their static {@link LanceError.code}. */
code?: string;
requestId?: string;
statusCode?: number;
/** Machine-readable code reported by a remote server, when it sent one. */
errorCode?: string;
resourceKind?: string;
resourceName?: string;
namespacePath?: string[];
tableName?: string;
columnName?: string;
databaseName?: string;
indexName?: string;
functionName?: string;
path?: string;
jobId?: string;
sqlJobId?: string;
jobRequestId?: string;
grpcCode?: number;
phase?: string;
retryable?: boolean;
requestFailures?: number;
maxRequestFailures?: number;
connectFailures?: number;
maxConnectFailures?: number;
readFailures?: number;
maxReadFailures?: number;
}
interface ErrorPayload {
code?: unknown;
requestId?: unknown;
statusCode?: unknown;
errorCode?: unknown;
resourceKind?: unknown;
resourceName?: unknown;
namespacePath?: unknown;
tableName?: unknown;
columnName?: unknown;
databaseName?: unknown;
indexName?: unknown;
functionName?: unknown;
path?: unknown;
jobId?: unknown;
sqlJobId?: unknown;
jobRequestId?: unknown;
grpcCode?: unknown;
phase?: unknown;
retryable?: unknown;
requestFailures?: unknown;
maxRequestFailures?: unknown;
connectFailures?: unknown;
maxConnectFailures?: unknown;
readFailures?: unknown;
maxReadFailures?: unknown;
}
/**
* Base class for errors raised by the LanceDB native core.
*
* Subclasses exist so application code can branch with `instanceof`. A kind
* that does not have its own class is still a {@link LanceError}; `code` then
* carries the Rust variant name.
*
* Stream-time failures and native constructor validation can still arrive as a
* plain `Error`. Handle that case as a fallback.
*
* ```ts
* import * as lancedb from "@lancedb/lancedb";
*
* try {
* await db.openTable("missing");
* } catch (error) {
* if (error instanceof lancedb.TableNotFoundError) {
* error.tableName; // "missing"
* error.cause; // underlying error, when Rust supplied one
* } else if (error instanceof Error) {
* // Stream-time failures and native constructor validation can still
* // arrive untyped.
* error.message;
* }
* }
* ```
*/
export class LanceError extends Error {
static readonly code: string = "Error";
readonly code: string;
readonly requestId?: string;
readonly statusCode?: number;
readonly errorCode?: string;
readonly resourceKind?: string;
readonly resourceName?: string;
readonly namespacePath?: string[];
readonly tableName?: string;
readonly columnName?: string;
readonly databaseName?: string;
readonly indexName?: string;
readonly functionName?: string;
readonly path?: string;
readonly jobId?: string;
readonly sqlJobId?: string;
readonly jobRequestId?: string;
readonly grpcCode?: number;
readonly phase?: string;
readonly retryable?: boolean;
readonly requestFailures?: number;
readonly maxRequestFailures?: number;
readonly connectFailures?: number;
readonly maxConnectFailures?: number;
readonly readFailures?: number;
readonly maxReadFailures?: number;
constructor(message: string, options?: LanceErrorOptions) {
super(message, { cause: options?.cause });
const ctor = new.target as unknown as { code?: string };
this.name = new.target.name;
this.code = options?.code ?? ctor.code ?? LanceError.code;
this.requestId = options?.requestId;
this.statusCode = options?.statusCode;
this.errorCode = options?.errorCode;
this.resourceKind = options?.resourceKind;
this.resourceName = options?.resourceName;
this.namespacePath = options?.namespacePath;
this.tableName = options?.tableName;
this.columnName = options?.columnName;
this.databaseName = options?.databaseName;
this.indexName = options?.indexName;
this.functionName = options?.functionName;
this.path = options?.path;
this.jobId = options?.jobId;
this.sqlJobId = options?.sqlJobId;
this.jobRequestId = options?.jobRequestId;
this.grpcCode = options?.grpcCode;
this.phase = options?.phase;
this.retryable = options?.retryable;
this.requestFailures = options?.requestFailures;
this.maxRequestFailures = options?.maxRequestFailures;
this.connectFailures = options?.connectFailures;
this.maxConnectFailures = options?.maxConnectFailures;
this.readFailures = options?.readFailures;
this.maxReadFailures = options?.maxReadFailures;
Object.defineProperty(this, LANCE_ERROR_MARK, { value: true });
}
}
/** Input rejected before it reached storage. */
export class InvalidInputError extends LanceError {
static override readonly code: string = "InvalidInput";
}
/** A table name failed validation. */
export class InvalidTableNameError extends InvalidInputError {
static override readonly code = "InvalidTableName";
}
/** A computed-column or SQL expression was rejected. */
export class InvalidExpressionError extends InvalidInputError {
static override readonly code = "InvalidExpression";
}
/** The data or query does not match the expected schema. */
export class SchemaError extends InvalidInputError {
static override readonly code = "Schema";
}
/** The named table is not a materialized view. */
export class NotAMaterializedViewError extends InvalidInputError {
static override readonly code = "NotAMaterializedView";
}
/** The named table does not exist. */
export class TableNotFoundError extends LanceError {
static override readonly code = "TableNotFound";
}
/** The named table is present but could not be loaded. */
export class TableCorruptedError extends LanceError {
static override readonly code = "TableCorrupted";
}
/** A table with this name already exists. */
export class TableAlreadyExistsError extends LanceError {
static override readonly code = "TableAlreadyExists";
}
/** The named database does not exist. */
export class DatabaseNotFoundError extends LanceError {
static override readonly code = "DatabaseNotFound";
}
/** A database with this name already exists. */
export class DatabaseAlreadyExistsError extends LanceError {
static override readonly code = "DatabaseAlreadyExists";
}
/** The named index does not exist. */
export class IndexNotFoundError extends LanceError {
static override readonly code = "IndexNotFound";
}
/** The named embedding function is not registered. */
export class EmbeddingFunctionNotFoundError extends LanceError {
static override readonly code = "EmbeddingFunctionNotFound";
}
/** The named column does not exist. */
export class ColumnNotFoundError extends LanceError {
static override readonly code: string = "ColumnNotFound";
}
/**
* A query referenced a field the schema does not contain.
*
* This is also a {@link ColumnNotFoundError}. `code` remains `"FieldNotFound"`
* so callers can tell a schema-qualified miss from a plain missing column.
*/
export class FieldNotFoundError extends ColumnNotFoundError {
static override readonly code = "FieldNotFound";
}
/** A column with this name already exists. */
export class ColumnAlreadyExistsError extends LanceError {
static override readonly code = "ColumnAlreadyExists";
}
/** The named column is not a computed column. */
export class NotAComputedColumnError extends LanceError {
static override readonly code = "NotAComputedColumn";
}
/** The operation is not implemented for this table or build. */
export class NotSupportedError extends LanceError {
static override readonly code = "NotSupported";
}
/** A local operation exceeded its time limit. */
export class TimeoutError extends LanceError {
static override readonly code = "Timeout";
}
/** An unclassified failure inside the LanceDB runtime. */
export class LanceRuntimeError extends LanceError {
static override readonly code = "Runtime";
}
/** Creating a dataset directory failed. */
export class CreateDirError extends LanceError {
static override readonly code = "CreateDir";
}
/** Object storage returned an error. */
export class ObjectStoreError extends LanceError {
static override readonly code = "ObjectStore";
}
/** The Lance format layer returned an error. `code` is `"Lance"`. */
export class LanceFormatError extends LanceError {
static override readonly code = "Lance";
}
/** Arrow returned an error while reading or writing batches. */
export class LanceArrowError extends LanceError {
static override readonly code = "Arrow";
}
/** A caller-supplied callback or external library failed. */
export class ExternalError extends LanceError {
static override readonly code = "External";
}
/** A LanceDB error that does not fit a more specific kind. */
export class OtherError extends LanceError {
static override readonly code = "Other";
}
/** An HTTP call to LanceDB Cloud or Enterprise failed. */
export class HttpError extends LanceError {
static override readonly code = "Http";
}
/** A remote call exhausted its retry policy. `cause` is the last HTTP error. */
export class RetryError extends LanceError {
static override readonly code = "Retry";
}
/** A remote SQL call failed. `grpcCode` is the numeric gRPC status. */
export class SqlError extends LanceError {
static override readonly code = "Sql";
}
/** An asynchronous job finished in the failed state. */
export class JobFailedError extends LanceError {
static override readonly code = "JobFailed";
}
/** An asynchronous job was cancelled. */
export class JobCancelledError extends LanceError {
static override readonly code = "JobCancelled";
}
/** The named job does not exist. */
export class JobNotFoundError extends LanceError {
static override readonly code = "JobNotFound";
}
type LanceErrorConstructor = new (
message: string,
options?: LanceErrorOptions,
) => LanceError;
const ERROR_CLASSES = new Map<string, LanceErrorConstructor>([
["InvalidInput", InvalidInputError],
["InvalidTableName", InvalidTableNameError],
["InvalidExpression", InvalidExpressionError],
["Schema", SchemaError],
["NotAMaterializedView", NotAMaterializedViewError],
["TableNotFound", TableNotFoundError],
["TableCorrupted", TableCorruptedError],
["TableAlreadyExists", TableAlreadyExistsError],
["DatabaseNotFound", DatabaseNotFoundError],
["DatabaseAlreadyExists", DatabaseAlreadyExistsError],
["IndexNotFound", IndexNotFoundError],
["EmbeddingFunctionNotFound", EmbeddingFunctionNotFoundError],
["ColumnNotFound", ColumnNotFoundError],
["FieldNotFound", FieldNotFoundError],
["ColumnAlreadyExists", ColumnAlreadyExistsError],
["NotAComputedColumn", NotAComputedColumnError],
["NotSupported", NotSupportedError],
["Timeout", TimeoutError],
["Runtime", LanceRuntimeError],
["CreateDir", CreateDirError],
["ObjectStore", ObjectStoreError],
["Lance", LanceFormatError],
["Arrow", LanceArrowError],
["External", ExternalError],
["Other", OtherError],
["Http", HttpError],
["Retry", RetryError],
["Sql", SqlError],
["JobFailed", JobFailedError],
["JobCancelled", JobCancelledError],
["JobNotFound", JobNotFoundError],
]);
/** True when `error` was raised by the LanceDB native core. */
export function isLanceError(error: unknown): error is LanceError {
return error instanceof LanceError;
}
/** True for table, database, and column create conflicts. */
export function isAlreadyExistsError(
error: unknown,
): error is
| TableAlreadyExistsError
| DatabaseAlreadyExistsError
| ColumnAlreadyExistsError {
return (
error instanceof TableAlreadyExistsError ||
error instanceof DatabaseAlreadyExistsError ||
error instanceof ColumnAlreadyExistsError
);
}
/**
* Rebuild a native rejection as a {@link LanceError} subclass.
*
* Errors that did not come from Rust, including plain `Error`s thrown by the
* TypeScript layer, are returned unchanged.
*
* An error already translated by another SDK load is not an `instanceof` this
* load's classes. Its kind and fields are copied onto a new subclass so
* `instanceof` and metadata such as `tableName` stay valid here.
*/
export function materializeLanceError(error: unknown, depth = 0): unknown {
if (depth > MAX_CAUSE_DEPTH) {
return error;
}
if (error instanceof LanceError) {
return error;
}
if (isMarkedLanceError(error)) {
return rebuildMarked(error, depth);
}
if (!isErrorLike(error)) {
return error;
}
const cause =
error.cause === undefined
? undefined
: materializeLanceError(error.cause, depth + 1);
const match = HEADER.exec(error.message);
if (match === null) {
// Native addons create Error in Node's realm. Jest and other vm contexts
// have a different Error constructor, so preserve the message on a local one.
return error instanceof Error && cause === error.cause
? error
: copyForeignError(error, cause);
}
let payload: ErrorPayload;
try {
payload = JSON.parse(match[1]) as ErrorPayload;
} catch {
return error instanceof Error ? error : copyForeignError(error, cause);
}
if (typeof payload.code !== "string" || payload.code.length === 0) {
return error instanceof Error ? error : copyForeignError(error, cause);
}
const message = error.message.slice(match[0].length) || payload.code;
const wrapped = createLanceError(
message,
payload.code,
payloadOptions(payload, cause),
);
copyStack(error, wrapped);
return wrapped;
}
function isMarkedLanceError(
error: unknown,
): error is Error & { code: string; cause?: unknown } {
if (typeof error !== "object" || error === null) {
return false;
}
const candidate = error as {
code?: unknown;
message?: unknown;
[LANCE_ERROR_MARK]?: unknown;
};
return (
candidate[LANCE_ERROR_MARK] === true &&
typeof candidate.message === "string" &&
typeof candidate.code === "string" &&
candidate.code.length > 0
);
}
function rebuildMarked(
error: Error & { code: string; cause?: unknown },
depth: number,
): LanceError {
const cause =
error.cause === undefined
? undefined
: materializeLanceError(error.cause, depth + 1);
const wrapped = createLanceError(
error.message,
error.code,
payloadOptions(instancePayload(error), cause),
);
copyStack(error, wrapped);
return wrapped;
}
function createLanceError(
message: string,
code: string,
options: LanceErrorOptions,
): LanceError {
const Ctor = ERROR_CLASSES.get(code);
if (Ctor === undefined) {
return new LanceError(message, { ...options, code });
}
return new Ctor(message, { ...options, code });
}
function instancePayload(error: object): ErrorPayload {
const source = error as Record<string, unknown>;
const payload: ErrorPayload = {};
for (const key of METADATA_KEYS) {
if (source[key] !== undefined) {
payload[key] = source[key];
}
}
return payload;
}
function copyStack(error: { stack?: unknown }, wrapped: LanceError): void {
if (typeof error.stack !== "string") {
return;
}
const newline = error.stack.indexOf("\n");
const frames = newline === -1 ? "" : error.stack.slice(newline);
wrapped.stack = `${wrapped.name}: ${wrapped.message}${frames}`;
}
function isErrorLike(value: unknown): value is Error {
if (value instanceof Error) {
return true;
}
if (typeof value !== "object" || value === null) {
return false;
}
const candidate = value as { message?: unknown; name?: unknown };
return (
typeof candidate.message === "string" && typeof candidate.name === "string"
);
}
function copyForeignError(error: Error, cause: unknown): Error {
const copy = new Error(error.message, { cause });
copy.name = error.name;
if (typeof error.stack === "string") {
copy.stack = error.stack;
}
const code = (error as { code?: unknown }).code;
if (typeof code === "string") {
(copy as { code?: string }).code = code;
}
return copy;
}
function payloadOptions(
payload: ErrorPayload,
cause: unknown,
): LanceErrorOptions {
return {
cause,
requestId: asString(payload.requestId),
statusCode: asNumber(payload.statusCode),
errorCode: asString(payload.errorCode),
resourceKind: asString(payload.resourceKind),
resourceName: asString(payload.resourceName),
namespacePath: asStringArray(payload.namespacePath),
tableName: asString(payload.tableName),
columnName: asString(payload.columnName),
databaseName: asString(payload.databaseName),
indexName: asString(payload.indexName),
functionName: asString(payload.functionName),
path: asString(payload.path),
jobId: asString(payload.jobId),
sqlJobId: asString(payload.sqlJobId),
jobRequestId: asString(payload.jobRequestId),
grpcCode: asNumber(payload.grpcCode),
phase: asString(payload.phase),
retryable: asBoolean(payload.retryable),
requestFailures: asNumber(payload.requestFailures),
maxRequestFailures: asNumber(payload.maxRequestFailures),
connectFailures: asNumber(payload.connectFailures),
maxConnectFailures: asNumber(payload.maxConnectFailures),
readFailures: asNumber(payload.readFailures),
maxReadFailures: asNumber(payload.maxReadFailures),
};
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value)
? value
: undefined;
}
function asBoolean(value: unknown): boolean | undefined {
return typeof value === "boolean" ? value : undefined;
}
function asStringArray(value: unknown): string[] | undefined {
if (
!Array.isArray(value) ||
!value.every((item) => typeof item === "string")
) {
return undefined;
}
return value;
}
/**
* Wrap the native module so Rust errors surface as {@link LanceError}s.
*
* Called while the package entrypoint loads. Idempotent within one load.
* A later load replaces these wrappers and calls the original native function,
* so translation uses that load's classes instead of nesting on a previous one.
*/
export function installLanceErrorTranslation(moduleNamespace: object): void {
for (const key of Object.getOwnPropertyNames(moduleNamespace)) {
const value = (moduleNamespace as Record<string, unknown>)[key];
if (typeof value !== "function") {
continue;
}
const fn = value as AnyFn;
if (isNativeClass(fn)) {
wrapOwnFunctions(fn);
wrapOwnFunctions((fn as { prototype: object }).prototype);
} else {
replaceFunction(moduleNamespace, key, fn);
}
}
}
function isNativeClass(value: AnyFn): boolean {
const prototype = (value as { prototype?: object }).prototype;
if (prototype != null) {
const hasMethods = Object.getOwnPropertyNames(prototype).some(
(name) => name !== "constructor",
);
if (hasMethods) {
return true;
}
}
// napi factory classes such as Index only expose static methods.
return Object.getOwnPropertyNames(value).some((name) => {
if (name === "length" || name === "name" || name === "prototype") {
return false;
}
const property = (value as unknown as Record<string, unknown>)[name];
return typeof property === "function";
});
}
function wrapOwnFunctions(owner: object): void {
for (const key of Object.getOwnPropertyNames(owner)) {
if (key === "prototype" || key === "length" || key === "name") {
continue;
}
const descriptor = Object.getOwnPropertyDescriptor(owner, key);
if (descriptor === undefined || typeof descriptor.value !== "function") {
continue;
}
replaceFunction(owner, key, descriptor.value as AnyFn);
}
}
function replaceFunction(owner: object, key: string, fn: AnyFn): void {
if (isWrapped(fn)) {
return;
}
const original = originalNative(fn);
const wrapped = function (this: unknown, ...args: unknown[]) {
const fail = (error: unknown): never => {
throw translatorFor(this)(error);
};
try {
const result = original.apply(this, args);
// Native promises are created in Node's realm. `instanceof Promise` is
// false when the caller is running in another realm, such as Jest.
if (isThenable(result)) {
return Promise.resolve(result).then((value) => value, fail);
}
return result;
} catch (error) {
fail(error);
}
};
Object.defineProperty(wrapped, "name", { value: original.name });
Object.defineProperty(wrapped, WRAPPED, { value: true });
Object.defineProperty(wrapped, ORIGINAL_FN, { value: original });
const descriptor = Object.getOwnPropertyDescriptor(owner, key);
try {
Object.defineProperty(owner, key, {
configurable: true,
enumerable: descriptor?.enumerable ?? false,
writable: descriptor?.writable ?? true,
value: wrapped,
});
} catch {
// A non-configurable native export keeps its original function.
}
}
function isWrapped(fn: AnyFn): boolean {
return Boolean((fn as unknown as Record<symbol, boolean>)[WRAPPED]);
}
function originalNative(fn: AnyFn): AnyFn {
const original = (fn as unknown as Record<symbol, unknown>)[ORIGINAL_FN];
return typeof original === "function" ? (original as AnyFn) : fn;
}
/**
* Remember which SDK load should translate errors thrown by `value`.
*
* Native classes are shared across loads. The load that wraps a native object
* in a TypeScript handle owns its errors, even if a later load replaces the
* method wrapper.
*/
export function bindErrorTranslator<T>(value: T): T {
if (
typeof value !== "object" ||
value === null ||
typeof (value as { then?: unknown }).then === "function"
) {
return value;
}
const host = translatorHost((value as object).constructor);
if (host === undefined) {
return value;
}
const map = translatorMap(host);
if (map !== undefined) {
map.set(value, materializeLanceError);
}
return value;
}
function translatorHost(ctor: unknown): TranslatorHost | undefined {
if (typeof ctor !== "function") {
return undefined;
}
return ctor as TranslatorHost;
}
function translatorMap(
host: TranslatorHost,
): WeakMap<object, ErrorTranslator> | undefined {
if (host[TRANSLATORS] != null) {
return host[TRANSLATORS];
}
try {
const map = new WeakMap<object, ErrorTranslator>();
Object.defineProperty(host, TRANSLATORS, { value: map });
return map;
} catch {
return undefined;
}
}
function translatorFor(target: unknown): ErrorTranslator {
if (typeof target === "object" && target !== null) {
const host = translatorHost((target as object).constructor);
const bound = host?.[TRANSLATORS]?.get(target);
if (bound !== undefined) {
return bound;
}
}
return materializeLanceError;
}
function isThenable(value: unknown): value is PromiseLike<unknown> {
return (
(typeof value === "object" || typeof value === "function") &&
value !== null &&
typeof (value as { then?: unknown }).then === "function"
);
}
+15
View File
@@ -0,0 +1,15 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import { installLanceErrorTranslation } from "./errors";
import * as native from "./native.js";
// Side effect: every native method rejects with a LanceError subclass.
// `import *` can be a copy of the CommonJS exports, so install on both the
// namespace and the original module object. Class prototypes are shared;
// free functions are not.
installLanceErrorTranslation(native);
const original = (native as { default?: object }).default;
if (original != null && original !== native) {
installLanceErrorTranslation(original);
}
+39
View File
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import "./errors_install";
import {
type Connection,
LocalConnection,
@@ -255,6 +257,43 @@ export {
IntoVector,
MultiVector,
} from "./arrow";
export {
ColumnAlreadyExistsError,
ColumnNotFoundError,
CreateDirError,
DatabaseAlreadyExistsError,
DatabaseNotFoundError,
EmbeddingFunctionNotFoundError,
ExternalError,
FieldNotFoundError,
HttpError,
IndexNotFoundError,
InvalidExpressionError,
InvalidInputError,
InvalidTableNameError,
JobCancelledError,
JobFailedError,
JobNotFoundError,
LanceArrowError,
LanceError,
LanceFormatError,
LanceRuntimeError,
NotAComputedColumnError,
NotAMaterializedViewError,
NotSupportedError,
ObjectStoreError,
OtherError,
RetryError,
SchemaError,
SqlError,
TableAlreadyExistsError,
TableCorruptedError,
TableNotFoundError,
TimeoutError,
isAlreadyExistsError,
isLanceError,
} from "./errors";
export type { LanceErrorOptions } from "./errors";
export { IntoSql, packBits } from "./util";
export { Expr, col, lit, litBool, litInt, func } from "./expr";
export type { ExprLike } from "./expr";
+9 -1
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
import { materializeLanceError } from "./errors";
import {
OAuthConfig as NativeOAuthConfig,
OAuthSession as NativeOAuthSession,
@@ -281,7 +282,14 @@ export class OAuthSession {
/** Create a session manager for the given OAuth configuration. */
constructor(config: OAuthConfig) {
this.inner = new NativeOAuthSession(config as unknown as NativeOAuthConfig);
try {
this.inner = new NativeOAuthSession(
config as unknown as NativeOAuthConfig,
);
} catch (error) {
// The native error translation wraps methods, not constructors.
throw materializeLanceError(error);
}
}
/**
+7 -3
View File
@@ -18,6 +18,7 @@ import {
vectorFromArray,
} from "./arrow";
import { isBlobDescriptorField, isBlobField } from "./blob";
import { bindErrorTranslator } from "./errors";
import { Expr } from "./expr";
import { type IvfPqOptions } from "./indices";
import {
@@ -378,7 +379,9 @@ export class QueryBase<
blobContext?: QueryBlobContext,
) {
if (inner !== undefined) {
this.setInner(inner);
this.setInner(
inner instanceof Promise ? inner : bindErrorTranslator(inner),
);
}
this.blobContext = blobContext;
}
@@ -400,8 +403,9 @@ export class QueryBase<
if (this.inner instanceof Promise) {
this.setInner(
this.inner.then((inner) => {
fn(inner);
return inner;
const bound = bindErrorTranslator(inner);
fn(bound);
return bound;
}),
);
} else {
+3 -2
View File
@@ -43,6 +43,7 @@ import {
toNativeBlobDescriptor,
} from "./blob";
import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry";
import { bindErrorTranslator } from "./errors";
import {
type FunctionErrorRowsOptions,
type FunctionFailedRow,
@@ -1798,7 +1799,7 @@ export class LocalTable extends Table {
constructor(inner: _NativeTable) {
super();
this.inner = inner;
this.inner = bindErrorTranslator(inner);
}
get name(): string {
return this.inner.name;
@@ -2985,7 +2986,7 @@ export class Branches {
* @hidden
*/
constructor(inner: NativeBranches) {
this.#inner = inner;
this.#inner = bindErrorTranslator(inner);
}
/** List all branches, mapping name to branch metadata. */
+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))
}
}