Hyperlinkv0.8.0-beta.28

Schema

Schema.Errorfunctioneffect/Schema.ts:9391
Error

Schema for JavaScript Error objects.

Details

Default JSON serializer:

Encodes an Error as an object with message, optional name, and optional cause properties, and decodes that object back into an Error. Stack traces are omitted by default for security. Pass { includeStack: true } to include stack traces, or { excludeCause: true } to omit causes.

constructors
Source effect/Schema.ts:939185 lines
export interface Error extends instanceOf<globalThis.Error> {
  readonly "Rebuild": Error
}

/**
 * Options for {@link Error} and {@link Defect}.
 *
 * @category options
 * @since 4.0.0
 */
export interface ErrorOptions {
  /**
   * Includes string stack traces in encoded `Error` values when set to `true`.
   *
   * @default false
   */
  readonly includeStack?: boolean | undefined
  /**
   * Excludes `Error.cause` values from encoded `Error` values when set to
   * `true`.
   *
   * @default false
   */
  readonly excludeCause?: boolean | undefined
}

type ErrorOptionsKey = 0 | 1 | 2 | 3

const getErrorOptionsKey = (options?: ErrorOptions): ErrorOptionsKey =>
  ((options?.includeStack === true ? 1 : 0) |
    (options?.excludeCause === true ? 2 : 0)) as ErrorOptionsKey

const getErrorOptions = (key: ErrorOptionsKey): ErrorOptions | undefined => {
  switch (key) {
    case 0:
      return undefined
    case 1:
      return { includeStack: true }
    case 2:
      return { excludeCause: true }
    case 3:
      return { includeStack: true, excludeCause: true }
  }
}

const errorSchemaCache: Array<Error | undefined> = []

/**
 * Schema for JavaScript `Error` objects.
 *
 * **Details**
 *
 * Default JSON serializer:
 *
 * Encodes an `Error` as an object with `message`, optional `name`, and optional
 * `cause` properties, and decodes that object back into an `Error`. Stack
 * traces are omitted by default for security. Pass `{ includeStack: true }` to
 * include stack traces, or `{ excludeCause: true }` to omit causes.
 *
 * @category constructors
 * @since 4.0.0
 */
export function Error(options?: ErrorOptions): Error {
  const key = getErrorOptionsKey(options)
  const cached = errorSchemaCache[key]
  if (cached !== undefined) {
    return cached
  }
  const normalizedOptions = getErrorOptions(key)
  const schema = instanceOf(globalThis.Error, {
    typeConstructor: {
      _tag: "Error",
      ...(normalizedOptions === undefined ? {} : { options: normalizedOptions })
    },
    generation: {
      runtime: normalizedOptions !== undefined ? `Schema.Error(${format(normalizedOptions)})` : `Schema.Error()`,
      Type: `globalThis.Error`
    },
    expected: "Error",
    toCodecJson: () => link<globalThis.Error>()(JsonError, SchemaTransformation.errorFromJsonError(normalizedOptions)),
    toArbitrary: () => (fc) => fc.string().map((message) => new globalThis.Error(message))
  })
  errorSchemaCache[key] = schema
  return schema
}
Referenced by 1 symbols