Skip to content

Commit e247c8e

Browse files
committed
Fix error message for incorrect subtype
1 parent 40ce5b4 commit e247c8e

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

src/Packet.cpp

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

2525
uint32_t subtype = 0;
2626
if (jsObject.Has("subtype")) {
27-
subtype = jsObject.Get("subtype").As<Napi::Number>().Uint32Value();
27+
if (jsObject.Get("subtype").IsNumber()) {
28+
subtype = jsObject.Get("subtype").As<Napi::Number>().Uint32Value();
29+
}
30+
else if (!jsObject.Get("subtype").IsUndefined()) {
31+
throw std::runtime_error("expected `subtype` to be a number");
32+
}
2833
}
2934

30-
// Check types are valid
3135
uint64_t timestamp = 0;
3236
try {
3337
timestamp = timestamp::FromJsValue(jsObject.Get("timestamp"), env);
@@ -44,9 +48,6 @@ namespace nbs {
4448
throw std::runtime_error(std::string("error in `type`: ") + ex.what());
4549
}
4650

47-
if (!jsObject.Get("subtype").IsNumber()) {
48-
throw std::runtime_error("expected `subtype` to be number");
49-
}
5051
if (!jsObject.Get("payload").IsBuffer()) {
5152
throw std::runtime_error("expected `payload` to be buffer object");
5253
}

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)