diff --git a/src/Packet.cpp b/src/Packet.cpp index 01b996e..86e64ff 100644 --- a/src/Packet.cpp +++ b/src/Packet.cpp @@ -26,10 +26,14 @@ namespace nbs { uint32_t subtype = 0; if (jsObject.Has("subtype")) { - subtype = jsObject.Get("subtype").As().Uint32Value(); + if (jsObject.Get("subtype").IsNumber()) { + subtype = jsObject.Get("subtype").As().Uint32Value(); + } + else if (!jsObject.Get("subtype").IsUndefined()) { + throw std::runtime_error("expected `subtype` to be a number"); + } } - // Check types are valid uint64_t timestamp = 0; try { timestamp = timestamp::FromJsValue(jsObject.Get("timestamp"), env); @@ -46,9 +50,6 @@ namespace nbs { throw std::runtime_error(std::string("error in `type`: ") + ex.what()); } - if (!jsObject.Get("subtype").IsNumber()) { - throw std::runtime_error("expected `subtype` to be number"); - } if (!jsObject.Get("payload").IsBuffer()) { throw std::runtime_error("expected `payload` to be buffer object"); } diff --git a/tests/test_encoder.js b/tests/test_encoder.js index f91b18a..387de6b 100644 --- a/tests/test_encoder.js +++ b/tests/test_encoder.js @@ -118,6 +118,19 @@ test('NbsEncoder.write() throws for invalid arguments', () => { 'NbsEncoder.write() throws with incorrect types for timestamp properties' ); + assert.throws( + () => { + encoder.write({ + timestamp: { seconds: 1897, nanos: 0 }, + type: pingType, + subtype: 'string', + payload: Buffer.from('ping.699', 'utf8'), + }); + }, + /invalid type for argument `packet`: expected `subtype` to be a number/, + 'NbsEncoder.write() throws with incorrect type for subtype' + ); + encoder.close(); }); });