From e247c8e83b6540f10cac1aa6c95d220b76bb37d8 Mon Sep 17 00:00:00 2001 From: Adrian Wann Date: Thu, 30 Jan 2025 08:57:37 +1100 Subject: [PATCH] Fix error message for incorrect subtype --- src/Packet.cpp | 11 ++++++----- tests/test_encoder.js | 13 +++++++++++++ 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/Packet.cpp b/src/Packet.cpp index c10fa83..71a10b5 100644 --- a/src/Packet.cpp +++ b/src/Packet.cpp @@ -24,10 +24,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); @@ -44,9 +48,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(); }); });