opusdev/vector-similarity-api
1
1import { BSON_MAJOR_VERSION } from './constants';2 3/**4 * @public5 * @category Error6 *7 * `BSONError` objects are thrown when BSON encounters an error.8 *9 * This is the parent class for all the other errors thrown by this library.10 */11export class BSONError extends Error {12 /**13 * @internal14 * The underlying algorithm for isBSONError may change to improve how strict it is15 * about determining if an input is a BSONError. But it must remain backwards compatible16 * with previous minors & patches of the current major version.17 */18 protected get bsonError(): true {19 return true;20 }21 22 override get name(): string {23 return 'BSONError';24 }25 26 constructor(message: string, options?: { cause?: unknown }) {27 super(message, options);28 }29 30 /**31 * @public32 *33 * All errors thrown from the BSON library inherit from `BSONError`.34 * This method can assist with determining if an error originates from the BSON library35 * even if it does not pass an `instanceof` check against this class' constructor.36 *37 * @param value - any javascript value that needs type checking38 */39 public static isBSONError(value: unknown): value is BSONError {40 return (41 value != null &&42 typeof value === 'object' &&43 'bsonError' in value &&44 value.bsonError === true &&45 // Do not access the following properties, just check existence46 'name' in value &&47 'message' in value &&48 'stack' in value49 );50 }51}52 53/**54 * @public55 * @category Error56 */57export class BSONVersionError extends BSONError {58 get name(): 'BSONVersionError' {59 return 'BSONVersionError';60 }61 62 constructor() {63 super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);64 }65}66 67/**68 * @public69 * @category Error70 *71 * An error generated when BSON functions encounter an unexpected input72 * or reaches an unexpected/invalid internal state73 *74 */75export class BSONRuntimeError extends BSONError {76 get name(): 'BSONRuntimeError' {77 return 'BSONRuntimeError';78 }79 80 constructor(message: string) {81 super(message);82 }83}84 85/**86 * @public87 * @category Error88 *89 * @experimental90 *91 * An error generated when BSON bytes are invalid.92 * Reports the offset the parser was able to reach before encountering the error.93 */94export class BSONOffsetError extends BSONError {95 public get name(): 'BSONOffsetError' {96 return 'BSONOffsetError';97 }98 99 public offset: number;100 101 constructor(message: string, offset: number, options?: { cause?: unknown }) {102 super(`${message}. offset: ${offset}`, options);103 this.offset = offset;104 }105}106 