From aaf832ad8529d20d413a943a16b0fbe598d240f5 Mon Sep 17 00:00:00 2001 From: Abe Tomoaki Date: Fri, 25 Oct 2024 08:50:23 +0900 Subject: [PATCH] Fix: JS: Improve error handling of batch addition Crash if there is an error in batch addition. Example: ``` const usearch = require('usearch'); const index = new usearch.Index({ metric: 'l2sq', connectivity: 16, dimensions: 3 }); index.add(42n, new Float32Array([0.2, 0.6, 0.4])); index.add( [41n, 42n, 43n], [[0.1, 0.6, 0.4], [0.2, 0.6, 0.4], [0.3, 0.6, 0.4]] ) ``` `42n` is duplicated, which causes an error, but then it crash. It seems that it is not better to throw an exception during the process, so we changed it to throw it after it is completed. --- javascript/lib.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/javascript/lib.cpp b/javascript/lib.cpp index b259f0b0..b82534a9 100644 --- a/javascript/lib.cpp +++ b/javascript/lib.cpp @@ -165,13 +165,16 @@ void CompiledIndex::Add(Napi::CallbackInfo const& ctx) { // Create an instance of the executor with the default number of threads auto run_parallel = [&](auto vectors) { + std::string error = ""; executor_stl_t executor; executor.fixed(tasks, [&](std::size_t /*thread_idx*/, std::size_t task_idx) { 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(); + error += ""; }); + if (error.size() > 0) + Napi::Error::New(ctx.Env(), error).ThrowAsJavaScriptException(); }; Napi::TypedArray vectors = ctx[1].As();