Skip to content

Commit

Permalink
Fix: Raise exceptions from add() in JS (#486)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
abetomo authored Oct 10, 2024
1 parent f315979 commit d6fd1eb
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
7 changes: 6 additions & 1 deletion javascript/lib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<CompiledIndex> {
public:
static Napi::Object Init(Napi::Env env, Napi::Object exports);
Expand Down Expand Up @@ -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<default_key_t>(keys[task_idx]), vectors + task_idx * native_->dimensions());
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();
});
};

Expand Down
18 changes: 18 additions & 0 deletions javascript/usearch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
}
);
});
});

0 comments on commit d6fd1eb

Please sign in to comment.