Skip to content

Commit

Permalink
Fix: JS: Improve error handling of batch addition
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
abetomo committed Oct 24, 2024
1 parent 113a786 commit aaf832a
Showing 1 changed file with 4 additions and 1 deletion.
5 changes: 4 additions & 1 deletion javascript/lib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<default_key_t>(keys[task_idx]),
vectors + task_idx * native_->dimensions());
if (!result)
Napi::Error::New(ctx.Env(), result.error.release()).ThrowAsJavaScriptException();
error += "<key:" + std::to_string(keys[task_idx]) + " message:" + result.error.release() + ">";
});
if (error.size() > 0)
Napi::Error::New(ctx.Env(), error).ThrowAsJavaScriptException();
};

Napi::TypedArray vectors = ctx[1].As<Napi::TypedArray>();
Expand Down

0 comments on commit aaf832a

Please sign in to comment.