Skip to content

Commit

Permalink
n-api: test and doc napi_throw() of a primitive
Browse files Browse the repository at this point in the history
Ensure that napi_throw() is able to throw a primitive value, and
document that it is able to throw any JavaScript value.

Fixes: nodejs/abi-stable-node#309
PR-URL: #20428
Reviewed-By: Michael Dawson <[email protected]>
Reviewed-By: Colin Ihrig <[email protected]>
  • Loading branch information
Gabriel Schulhof authored and MylesBorins committed May 4, 2018
1 parent da8bc6a commit ad793ab
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
4 changes: 2 additions & 2 deletions doc/api/n-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -344,11 +344,11 @@ added: v8.0.0
NODE_EXTERN napi_status napi_throw(napi_env env, napi_value error);
```
- `[in] env`: The environment that the API is invoked under.
- `[in] error`: The `napi_value` for the `Error` to be thrown.
- `[in] error`: The JavaScript value to be thrown.

Returns `napi_ok` if the API succeeded.

This API throws the JavaScript `Error` provided.
This API throws the JavaScript value provided.

#### napi_throw_error
<!-- YAML
Expand Down
12 changes: 12 additions & 0 deletions test/addons-napi/test_error/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,18 @@ assert.throws(() => {
test_error.throwTypeError();
}, /^TypeError: type error$/);

function testThrowArbitrary(value) {
assert.throws(() => {
test_error.throwArbitrary(value);
}, value);
}

testThrowArbitrary(42);
testThrowArbitrary({});
testThrowArbitrary([]);
testThrowArbitrary(Symbol('xyzzy'));
testThrowArbitrary(true);

common.expectsError(
() => test_error.throwErrorCode(),
{
Expand Down
9 changes: 9 additions & 0 deletions test/addons-napi/test_error/test_error.c
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,14 @@ napi_value createTypeErrorCode(napi_env env, napi_callback_info info) {
return result;
}

static napi_value throwArbitrary(napi_env env, napi_callback_info info) {
napi_value arbitrary;
size_t argc = 1;
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arbitrary, NULL, NULL));
NAPI_CALL(env, napi_throw(env, arbitrary));
return NULL;
}

napi_value Init(napi_env env, napi_value exports) {
napi_property_descriptor descriptors[] = {
DECLARE_NAPI_PROPERTY("checkError", checkError),
Expand All @@ -137,6 +145,7 @@ napi_value Init(napi_env env, napi_value exports) {
DECLARE_NAPI_PROPERTY("throwErrorCode", throwErrorCode),
DECLARE_NAPI_PROPERTY("throwRangeErrorCode", throwRangeErrorCode),
DECLARE_NAPI_PROPERTY("throwTypeErrorCode", throwTypeErrorCode),
DECLARE_NAPI_PROPERTY("throwArbitrary", throwArbitrary),
DECLARE_NAPI_PROPERTY("createError", createError),
DECLARE_NAPI_PROPERTY("createRangeError", createRangeError),
DECLARE_NAPI_PROPERTY("createTypeError", createTypeError),
Expand Down

0 comments on commit ad793ab

Please sign in to comment.