All files / kernel-errors/src BaseError.ts

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

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 61 62 63 64 65 66 67 68                                                                      153x   153x   153x 153x 153x     153x 24x     153x                             1x     137x  
import type { Json } from '@metamask/utils';
 
import { ErrorCode } from './constants.ts';
import type {
  MarshaledOcapError,
  OcapError,
  ErrorOptionsWithStack,
  MarshaledError,
} from './types.ts';
 
/**
 * Base class for all OCAP kernel errors.
 */
export class BaseError extends Error implements OcapError {
  public readonly code: ErrorCode;
 
  public readonly data: Json | undefined;
 
  /**
   * Creates a new BaseError instance.
   *
   * @param code - The error code identifying the type of error.
   * @param message - A human-readable description of the error.
   * @param options - Additional error options including cause, stack, and data.
   * @param options.data - Additional data about the error.
   * @param options.cause - The underlying error that caused the base error.
   * @param options.stack - The stack trace of the error.
   */
  constructor(
    code: ErrorCode,
    message: string,
    options: ErrorOptionsWithStack & {
      data?: Json;
    } = {},
  ) {
    const { data, cause, stack } = options;
 
    super(message, { cause });
 
    this.name = this.constructor.name;
    this.code = code;
    this.data = data;
 
    // override the stack property if provided
    if (stack) {
      this.stack = stack;
    }
 
    harden(this);
  }
 
  /**
   * A placeholder for unmarshal functionality. Should be implemented in subclasses.
   *
   * @param _marshaledError - The marshaled error to unmarshal.
   * @param _unmarshalErrorOptions - A function to unmarshal the error options.
   */
  public static unmarshal(
    _marshaledError: MarshaledOcapError,
    _unmarshalErrorOptions: (
      marshaledError: MarshaledError,
    ) => ErrorOptionsWithStack,
  ): BaseError {
    throw new Error('Unmarshal method not implemented');
  }
}
harden(BaseError);