All files / kernel-errors/src/marshal unmarshalError.ts

100% Statements 13/13
100% Branches 10/10
100% Functions 2/2
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                                  24x 4x           20x   20x   20x 19x     20x                       44x   44x 40x     44x 11x           44x    
import { isMarshaledOcapError } from './isMarshaledOcapError.ts';
import { errorClasses } from '../errors/index.ts';
import type {
  ErrorOptionsWithStack,
  MarshaledError,
  OcapError,
} from '../types.ts';
 
/**
 * Unmarshals a {@link MarshaledError} into an {@link Error}.
 *
 * @param marshaledError - The marshaled error to unmarshal.
 * @returns The unmarshaled error.
 */
export function unmarshalError(
  marshaledError: MarshaledError,
): Error | OcapError {
  if (isMarshaledOcapError(marshaledError)) {
    return errorClasses[marshaledError.code].unmarshal(
      marshaledError,
      unmarshalErrorOptions,
    );
  }
 
  const { cause, stack } = unmarshalErrorOptions(marshaledError);
 
  const error = new Error(marshaledError.message, { cause });
 
  if (stack) {
    error.stack = stack;
  }
 
  return error;
}
 
/**
 * Gets the error options from a marshaled error.
 *
 * @param marshaledError - The marshaled error to get the options from.
 * @returns The error options.
 */
export function unmarshalErrorOptions(
  marshaledError: MarshaledError,
): ErrorOptionsWithStack {
  const output: ErrorOptionsWithStack = {};
 
  if (marshaledError.stack) {
    output.stack = marshaledError.stack;
  }
 
  if (marshaledError.cause) {
    output.cause =
      typeof marshaledError.cause === 'string'
        ? marshaledError.cause
        : unmarshalError(marshaledError.cause);
  }
 
  return output;
}