ErrorObjectSerializer.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. /** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  6. /** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  7. class ErrorObjectSerializer {
  8. /**
  9. * @param {ErrorConstructor | EvalErrorConstructor | RangeErrorConstructor | ReferenceErrorConstructor | SyntaxErrorConstructor | TypeErrorConstructor} Type error type
  10. */
  11. constructor(Type) {
  12. this.Type = Type;
  13. }
  14. /**
  15. * @param {Error | EvalError | RangeError | ReferenceError | SyntaxError | TypeError} obj error
  16. * @param {ObjectSerializerContext} context context
  17. */
  18. serialize(obj, context) {
  19. context.write(obj.message);
  20. context.write(obj.stack);
  21. context.write(/** @type {Error & { cause: "unknown" }} */ (obj).cause);
  22. }
  23. /**
  24. * @param {ObjectDeserializerContext} context context
  25. * @returns {Error | EvalError | RangeError | ReferenceError | SyntaxError | TypeError} error
  26. */
  27. deserialize(context) {
  28. const err = new this.Type();
  29. err.message = context.read();
  30. err.stack = context.read();
  31. /** @type {Error & { cause: "unknown" }} */
  32. (err).cause = context.read();
  33. return err;
  34. }
  35. }
  36. module.exports = ErrorObjectSerializer;