Skip to content

Commit 96a29e2

Browse files
authored
Fix error message for incorrect subtype in encoder.write() (#16)
Fixes the error message that is shown when parsing a `NbsWritePacket` type with a `subtype` field that is the wrong type or explicitly set as undefined. It would previously print the error message "invalid type for argument \`packet\`: A number was expected". These changes make it now print "invalid type for argument \`packet\`: expected \`subtype\` to be a number".
1 parent 847eebe commit 96a29e2

2 files changed

Lines changed: 19 additions & 5 deletions

File tree

src/Packet.cpp

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,14 @@ namespace nbs {
2626

2727
uint32_t subtype = 0;
2828
if (jsObject.Has("subtype")) {
29-
subtype = jsObject.Get("subtype").As<Napi::Number>().Uint32Value();
29+
if (jsObject.Get("subtype").IsNumber()) {
30+
subtype = jsObject.Get("subtype").As<Napi::Number>().Uint32Value();
31+
}
32+
else if (!jsObject.Get("subtype").IsUndefined()) {
33+
throw std::runtime_error("expected `subtype` to be a number");
34+
}
3035
}
3136

32-
// Check types are valid
3337
uint64_t timestamp = 0;
3438
try {
3539
timestamp = timestamp::FromJsValue(jsObject.Get("timestamp"), env);
@@ -46,9 +50,6 @@ namespace nbs {
4650
throw std::runtime_error(std::string("error in `type`: ") + ex.what());
4751
}
4852

49-
if (!jsObject.Get("subtype").IsNumber()) {
50-
throw std::runtime_error("expected `subtype` to be number");
51-
}
5253
if (!jsObject.Get("payload").IsBuffer()) {
5354
throw std::runtime_error("expected `payload` to be buffer object");
5455
}

tests/test_encoder.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,19 @@ test('NbsEncoder.write() throws for invalid arguments', () => {
118118
'NbsEncoder.write() throws with incorrect types for timestamp properties'
119119
);
120120

121+
assert.throws(
122+
() => {
123+
encoder.write({
124+
timestamp: { seconds: 1897, nanos: 0 },
125+
type: pingType,
126+
subtype: 'string',
127+
payload: Buffer.from('ping.699', 'utf8'),
128+
});
129+
},
130+
/invalid type for argument `packet`: expected `subtype` to be a number/,
131+
'NbsEncoder.write() throws with incorrect type for subtype'
132+
);
133+
121134
encoder.close();
122135
});
123136
});

0 commit comments

Comments
 (0)