Skip to content

Commit ca2ee96

Browse files
committed
chore: finish error cleanup
1 parent d2f973c commit ca2ee96

File tree

3 files changed

+14
-8
lines changed

3 files changed

+14
-8
lines changed

src/error.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,8 @@ export class BSONOffsetError extends BSONError {
9898

9999
public offset: number;
100100

101-
constructor(message: string, offset: number) {
102-
super(`${message}. offset: ${offset}`);
101+
constructor(message: string, offset: number, options?: { cause?: unknown }) {
102+
super(`${message}. offset: ${offset}`, options);
103103
this.offset = offset;
104104
}
105105
}

src/parser/on_demand/parse_to_elements.ts

+11-3
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,14 @@ export type BSONElement = [
4545
length: number
4646
];
4747

48+
const getSize = (source: Uint8Array, offset: number) => {
49+
try {
50+
return NumberUtils.getSize(source, offset);
51+
} catch (cause) {
52+
throw new BSONOffsetError('BSON size cannot be negative', offset, { cause });
53+
}
54+
};
55+
4856
/**
4957
* Searches for null terminator of a BSON element's value (Never the document null terminator)
5058
* **Does not** bounds check since this should **ONLY** be used within parseToElements which has asserted that `bytes` ends with a `0x00`.
@@ -80,7 +88,7 @@ export function parseToElements(
8088
);
8189
}
8290

83-
const documentSize = NumberUtils.getSize(bytes, startOffset);
91+
const documentSize = getSize(bytes, startOffset);
8492

8593
if (documentSize > bytes.length - startOffset) {
8694
throw new BSONOffsetError(
@@ -144,15 +152,15 @@ export function parseToElements(
144152
type === BSONElementType.array ||
145153
type === BSONElementType.javascriptWithScope
146154
) {
147-
length = NumberUtils.getSize(bytes, offset);
155+
length = getSize(bytes, offset);
148156
} else if (
149157
type === BSONElementType.string ||
150158
type === BSONElementType.binData ||
151159
type === BSONElementType.dbPointer ||
152160
type === BSONElementType.javascript ||
153161
type === BSONElementType.symbol
154162
) {
155-
length = NumberUtils.getSize(bytes, offset) + 4;
163+
length = getSize(bytes, offset) + 4;
156164
if (type === BSONElementType.binData) {
157165
// binary subtype
158166
length += 1;

src/utils/number_utils.ts

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import { BSONOffsetError } from '../error';
2-
31
const FLOAT = new Float64Array(1);
42
const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
53

@@ -40,7 +38,7 @@ export type NumberUtils = {
4038
export const NumberUtils: NumberUtils = {
4139
getSize(source: Uint8Array, offset: number): number {
4240
if (source[offset + 3] > 127) {
43-
throw new BSONOffsetError('BSON size cannot be negative', offset);
41+
throw new RangeError(`Size cannot be negative at offset: ${offset}`);
4442
}
4543
return (
4644
source[offset] |

0 commit comments

Comments
 (0)