ErrorObjectSerializer.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. /** @import { ComplexSerializableType } from "./types" */
  6. /** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext<ComplexSerializableType[]>} ObjectDeserializerContext */
  7. /** @typedef {import("./ObjectMiddleware").ObjectSerializerContext<ComplexSerializableType[]>} ObjectSerializerContext */
  8. /** @typedef {Error & { cause?: unknown }} ErrorWithCause */
  9. class ErrorObjectSerializer {
  10. /**
  11. * Creates an instance of ErrorObjectSerializer.
  12. * @param {ErrorConstructor | EvalErrorConstructor | RangeErrorConstructor | ReferenceErrorConstructor | SyntaxErrorConstructor | TypeErrorConstructor} Type error type
  13. */
  14. constructor(Type) {
  15. this.Type = Type;
  16. }
  17. /**
  18. * Serializes this instance into the provided serializer context.
  19. * @param {Error | EvalError | RangeError | ReferenceError | SyntaxError | TypeError} obj error
  20. * @param {ObjectSerializerContext} context context
  21. */
  22. serialize(obj, context) {
  23. context.write(obj.message);
  24. context.write(obj.stack);
  25. context.write(
  26. /** @type {ComplexSerializableType} */
  27. (/** @type {ErrorWithCause} */ (obj).cause)
  28. );
  29. }
  30. /**
  31. * Restores this instance from the provided deserializer context.
  32. * @param {ObjectDeserializerContext} context context
  33. * @returns {Error | EvalError | RangeError | ReferenceError | SyntaxError | TypeError} error
  34. */
  35. deserialize(context) {
  36. const err = new this.Type();
  37. err.message = /** @type {string} */ (context.read());
  38. err.stack = /** @type {string | undefined} */ (context.read());
  39. /** @type {ErrorWithCause} */
  40. (err).cause = context.read();
  41. return err;
  42. }
  43. }
  44. module.exports = ErrorObjectSerializer;