From d6fd1eba21979cdb0fccce1257e76a99db600189 Mon Sep 17 00:00:00 2001 From: Abe Tomoaki Date: Thu, 10 Oct 2024 22:59:38 +0900 Subject: [PATCH] Fix: Raise exceptions from `add()` in JS (#486) For example, if you try to add the same key, it aborts. ``` terminate called after throwing an instance of 'std::runtime_error' what(): Duplicate keys not allowed in high-level wrappers Aborted (core dumped) ``` Improved error handling to throw JavaScript exceptions. --- javascript/lib.cpp | 7 ++++++- javascript/usearch.test.js | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/javascript/lib.cpp b/javascript/lib.cpp index 07346828..3f576533 100644 --- a/javascript/lib.cpp +++ b/javascript/lib.cpp @@ -20,6 +20,8 @@ using namespace unum::usearch; using namespace unum; +using add_result_t = typename index_dense_t::add_result_t; + class CompiledIndex : public Napi::ObjectWrap { public: static Napi::Object Init(Napi::Env env, Napi::Object exports); @@ -161,7 +163,10 @@ void CompiledIndex::Add(Napi::CallbackInfo const& ctx) { auto run_parallel = [&](auto vectors) { executor_stl_t executor; executor.fixed(tasks, [&](std::size_t /*thread_idx*/, std::size_t task_idx) { - native_->add(static_cast(keys[task_idx]), vectors + task_idx * native_->dimensions()); + add_result_t result = native_->add(static_cast(keys[task_idx]), + vectors + task_idx * native_->dimensions()); + if (!result) + Napi::Error::New(ctx.Env(), result.error.release()).ThrowAsJavaScriptException(); }); }; diff --git a/javascript/usearch.test.js b/javascript/usearch.test.js index 607ddcc6..80747763 100644 --- a/javascript/usearch.test.js +++ b/javascript/usearch.test.js @@ -104,3 +104,21 @@ test('Operations with invalid values', () => { } ); }); + +test('Invalid operations', async (t) => { + await t.test('Add the same keys', () => { + const index = new usearch.Index({ + metric: "l2sq", + connectivity: 16, + dimensions: 3, + }); + index.add(42n, new Float32Array([0.2, 0.6, 0.4])); + assert.throws( + () => index.add(42n, new Float32Array([0.2, 0.6, 0.4])), + { + name: 'Error', + message: 'Duplicate keys not allowed in high-level wrappers' + } + ); + }); +});