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