error.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { BSON_MAJOR_VERSION } from './constants';
  2. /**
  3. * @public
  4. * @category Error
  5. *
  6. * `BSONError` objects are thrown when BSON ecounters an error.
  7. *
  8. * This is the parent class for all the other errors thrown by this library.
  9. */
  10. export class BSONError extends Error {
  11. /**
  12. * @internal
  13. * The underlying algorithm for isBSONError may change to improve how strict it is
  14. * about determining if an input is a BSONError. But it must remain backwards compatible
  15. * with previous minors & patches of the current major version.
  16. */
  17. protected get bsonError(): true {
  18. return true;
  19. }
  20. override get name(): string {
  21. return 'BSONError';
  22. }
  23. constructor(message: string) {
  24. super(message);
  25. }
  26. /**
  27. * @public
  28. *
  29. * All errors thrown from the BSON library inherit from `BSONError`.
  30. * This method can assist with determining if an error originates from the BSON library
  31. * even if it does not pass an `instanceof` check against this class' constructor.
  32. *
  33. * @param value - any javascript value that needs type checking
  34. */
  35. public static isBSONError(value: unknown): value is BSONError {
  36. return (
  37. value != null &&
  38. typeof value === 'object' &&
  39. 'bsonError' in value &&
  40. value.bsonError === true &&
  41. // Do not access the following properties, just check existence
  42. 'name' in value &&
  43. 'message' in value &&
  44. 'stack' in value
  45. );
  46. }
  47. }
  48. /**
  49. * @public
  50. * @category Error
  51. */
  52. export class BSONVersionError extends BSONError {
  53. get name(): 'BSONVersionError' {
  54. return 'BSONVersionError';
  55. }
  56. constructor() {
  57. super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
  58. }
  59. }
  60. /**
  61. * @public
  62. * @category Error
  63. *
  64. * An error generated when BSON functions encounter an unexpected input
  65. * or reaches an unexpected/invalid internal state
  66. *
  67. */
  68. export class BSONRuntimeError extends BSONError {
  69. get name(): 'BSONRuntimeError' {
  70. return 'BSONRuntimeError';
  71. }
  72. constructor(message: string) {
  73. super(message);
  74. }
  75. }