Skip to content

deepbox/core

Errors, Warnings & Logging

The DeepboxError hierarchy, a filterable warning system, and a small verbosity-based logger.

  • Errors
  • Warnings
  • Logging

Overview

  • Every error class extends DeepboxError directly, and no class extends another. instanceof ShapeError therefore does not match a BroadcastError. Catch the specific class, or DeepboxError to catch them all.
  • Shape mismatches in tensor operations throw ShapeError. BroadcastError is exported for your own code, but the library reports failed broadcasts as ShapeError. Mixed devices, a missing backend, an operation a device does not support and a disposed tensor throw DeviceError.
  • warn(message, category, source) sends a warning to the handler set with setWarningHandler, or to console.warn. filterWarnings(action, { category, message }) sets what happens (ignore, error, once, always, default), and the most recently added filter wins. catchWarnings(fn) collects the warnings of a synchronous function. A few estimators emit ConvergenceWarning or UserWarning.
  • Logger(verbose, source) takes a level from 0 (silent) to 3 (trace) and prints through console.log, or through the handler set with setLogHandler. The library does not log through it. It is a utility for your own code.

Types

7

ConvergenceErrorDetails

type

Details for convergence failures.

  • readonly iterations?: number
  • readonly tolerance?: number
  • readonly cause?: unknown

ShapeErrorDetails

type

Details about a shape mismatch error.

  • readonly expected?: Shape
  • readonly received?: Shape
  • readonly context?: string
  • readonly cause?: unknown

LogEntry

interface

A log entry produced by the logger.

  • readonly level: VerboseLevel
  • readonly message: string
  • readonly timestamp: number

    Milliseconds since the Unix epoch, from Date.now().

  • readonly source?: string

    Name of the component that produced the entry (the Logger's source).

VerboseLevel

type

Verbosity level type (0 = silent, higher = more verbose).

type VerboseLevel = 0 | 1 | 2 | 3;

DeepboxWarning

interface

Structured warning emitted by Deepbox components.

  • category: WarningCategory
  • message: string
  • source?: string | undefined

WarningAction

type

Action to take when a warning is emitted.

- "default" and "always": emit every time - "ignore": drop the warning - "error": throw a DeepboxError instead of emitting - "once": emit the first occurrence of each category and message only

type WarningAction = "default" | "error" | "ignore" | "always" | "once";

WarningCategory

type

Category of a Deepbox warning, mirroring scikit-learn's warning categories.

type WarningCategory = "ConvergenceWarning" | "DataConversionWarning" | "UndefinedMetricWarning" | "FitFailedWarning" | "UserWarning";

Classes

13

BroadcastError

extends DeepboxError

Error thrown when tensor shapes cannot be broadcast together.

Broadcasting allows operations on tensors of different shapes by automatically expanding dimensions. This error occurs when shapes are incompatible.

Example
// Broadcasting (3, 4) and (4,) works -> (3, 4)// Broadcasting (3, 4) and (3,) failsif (!canBroadcast(shape1, shape2)) {  throw new BroadcastError(shape1, shape2);}
Members (4)
  • constructor(shape1: Shape, shape2: Shape, context?: string, options?: { readonly cause?: unknown; })
  • name: string
  • readonly shape1: Shape

    The first shape involved in the broadcast operation

  • readonly shape2: Shape

    The second shape involved in the broadcast operation

ConvergenceError

extends DeepboxError

Error thrown when an iterative algorithm fails to converge within the maximum allowed iterations.

This is a thrown exception that extends DeepboxError; callers should handle it with standard try/catch.

Example
if (iterations >= maxIterations) {  throw new ConvergenceError(    `Algorithm did not converge after ${maxIterations} iterations`  );}
Members (4)
  • constructor(message: string, details?: ConvergenceErrorDetails)
  • name: string
  • readonly iterations?: number

    Number of iterations completed before convergence failure

  • readonly tolerance?: number

    Tolerance value used for convergence check

DataValidationError

extends DeepboxError

Error thrown when data validation fails.

Used for input data that doesn't meet expected format or constraints.

Example
if (!Array.isArray(data)) {  throw new DataValidationError('Expected array input');}
Members (1)
  • name: string

DeepboxError

extends Error

Base class for all Deepbox-specific errors.

Provides a stable instanceof DeepboxError discriminator and consistent cause chaining.

The cause property is only defined on the instance when a cause was passed, so "cause" in error reliably tells whether one was supplied.

Members (2)
  • constructor(message?: string, options?: { readonly cause?: unknown; })
  • name: string

DeviceError

extends DeepboxError

Error thrown when an operation is requested on an unsupported or unavailable compute device.

This is intended for device selection / dispatch layers (e.g. attempting to use webgpu in an environment where WebGPU is not available).

Members (1)
  • name: string

    Discriminator name for this error type.

DTypeError

extends DeepboxError

Error thrown when a requested dtype is unsupported or cannot be handled by the current implementation.

This is used in low-level dtype utilities (e.g. mapping a DType to a TypedArray constructor) to provide a stable, package-specific error type.

Members (1)
  • name: string

    Discriminator name for this error type.

IndexError

extends DeepboxError

Error thrown when an invalid index is used to access tensor elements.

Example
if (index < 0 || index >= length) {  throw new IndexError(`Index ${index} is out of bounds for length ${length}`);}
Members (4)
  • constructor(message: string, details?: { readonly index?: number; readonly validRange?: readonly [ number, number ]; readonly cause?: unknown; })
  • name: string
  • readonly index?: number

    The invalid index value

  • readonly validRange?: readonly [ number, number ]

    The valid range for the index

InvalidParameterError

extends DeepboxError

Error thrown when invalid parameters are passed to a function or method.

Example
function kmeans(k: number, maxIter: number) {  if (k <= 0) {    throw new InvalidParameterError('k must be positive', 'k', k);  }  // ... algorithm logic}
Members (4)
  • constructor(message: string, parameterName?: string, value?: unknown, options?: { readonly cause?: unknown; })
  • name: string
  • readonly parameterName?: string

    The name of the invalid parameter

  • readonly value?: unknown

    The invalid value that was provided

MemoryError

extends DeepboxError

Error thrown when memory allocation fails or memory limits are exceeded.

Example
if (requestedBytes > MAX_MEMORY) {  throw new MemoryError(`Cannot allocate ${requestedBytes} bytes`);}
Members (4)
  • constructor(message: string, details?: { readonly requestedBytes?: number; readonly availableBytes?: number; readonly cause?: unknown; })
  • name: string
  • readonly requestedBytes?: number

    The amount of memory requested in bytes

  • readonly availableBytes?: number

    The amount of memory available in bytes

NotFittedError

extends DeepboxError

Error thrown when a model or estimator is used before being fitted.

Thrown when a model is used before calling fit().

Example
class MyModel {  private fitted = false;   fit(X: Tensor, y: Tensor) {    // ... fitting logic    this.fitted = true;  }   predict(X: Tensor) {    if (!this.fitted) {      throw new NotFittedError('Model must be fitted before prediction');    }    // ... prediction logic  }}
Members (3)
  • constructor(message: string, modelName?: string, options?: { readonly cause?: unknown; })
  • name: string
  • readonly modelName?: string

    The name of the model or estimator that was not fitted

NotImplementedError

extends DeepboxError

Error thrown when a method or code path exists in the public API but is not implemented yet.

Use this instead of a generic Error so callers can reliably detect this specific capability gap.

Members (2)
  • constructor(message?: string, options?: { readonly cause?: unknown; })

    Create a new NotImplementedError.

  • name: string

    Discriminator name for this error type.

ShapeError

extends DeepboxError

Error thrown when tensor shapes are incompatible or invalid.

This error is used throughout the framework when operations require specific tensor shapes that don't match the provided tensors.

Example
import { ShapeError } from 'deepbox/core'; if (tensor.shape[0] !== expectedRows) {  throw ShapeError.mismatch([expectedRows, cols], tensor.shape, 'matrix multiplication');}
Members (6)
  • constructor(message: string, details?: ShapeErrorDetails)
  • name: string
  • readonly expected: Shape | undefined
  • readonly received: Shape | undefined
  • readonly context: string | undefined
  • static mismatch(expected: Shape, received: Shape, context?: string): ShapeError

    Create a ShapeError for a shape mismatch.

Logger

Logger for Deepbox models and utilities.

Example
import { Logger } from 'deepbox/core'; const log = new Logger(1, 'KMeans');log.info('Converged in 15 iterations');    // prints at verbosity >= 1log.debug('Iteration 5: inertia=23.4');    // prints at verbosity >= 2log.trace('Distance matrix computed');      // prints at verbosity >= 3
Members (8)
  • constructor(verbose: VerboseLevel, source: string)
  • level: VerboseLevel

    The configured verbosity level.

  • info(message: string): void

    Log at level 1 (summary).

  • debug(message: string): void

    Log at level 2 (per-iteration progress).

  • trace(message: string): void

    Log at level 3 (trace/debug detail).

  • log(level: VerboseLevel, message: string): void

    Log a message at a specific level.

  • getEntries(): readonly LogEntry[]

    Get the recorded log entries in chronological order (regardless of verbosity).

  • clear(): void

    Clear all recorded entries.

Functions

7

getLogHandler

function getLogHandler(): LogHandler | undefined;

Get the current global log handler (undefined = console.log default).

Returns

LogHandler | undefined

setLogHandler

function setLogHandler(handler: LogHandler | undefined): void;

Set a global log handler for all Logger instances. The handler is called only for entries that pass the logger's verbosity level. Pass undefined to revert to default (console.log).

Parameters

handler
LogHandler | undefined

catchWarnings

function catchWarnings(fn: () => void): DeepboxWarning[];

Run fn and return the warnings that reached the handler while it ran.

Filters still apply: ignored warnings are not collected and "error" filters still throw. The previous handler is restored afterwards, also when fn throws. fn must be synchronous; warnings emitted after it returns are not collected.

Parameters

fn
() => void
Synchronous function to run

Returns

DeepboxWarning[]Collected warnings in emission order

filterWarnings

function filterWarnings(action: WarningAction, options?: { category?: WarningCategory; message?: string | RegExp; }): void;

Add a warning filter. Filters added later take precedence over earlier ones.

Parameters

action
WarningAction
What to do: "default", "error", "ignore", "always", "once"
optionsoptional
{ category?: WarningCategory; message?: string | RegExp; }
Optional category and message pattern to match. A string message is treated as a regular expression source and matched anywhere in the message.

Throws

  • InvalidParameterErrorIf action is unknown or the message pattern is not a valid regular expression

resetWarnings

function resetWarnings(): void;

Remove all warning filters and forget which "once" warnings were already emitted.

setWarningHandler

function setWarningHandler(handler: WarningHandler | undefined): void;

Set a custom warning handler (replaces console.warn). Pass undefined to restore console.warn.

Parameters

handler
WarningHandler | undefined

warn

function warn(message: string, category?: WarningCategory, source?: string): void;

Issue a warning. Behavior depends on current filters.

The most recently added filter that matches the category and message wins. Without a matching filter the warning goes to the custom handler (see setWarningHandler) or to console.warn.

Parameters

message
string
Warning message
categoryoptional
WarningCategory
Warning category (default: "UserWarning")
sourceoptional
string
Optional source identifier (e.g. function name)

Throws

  • DeepboxErrorIf a matching filter has the "error" action
core-errors.ts
import {  DeepboxError,  Logger,  ShapeError,  catchWarnings,  filterWarnings,  resetWarnings,  warn,} from "deepbox/core"; const logger = new Logger(1, "docs");logger.info("Deepbox runtime ready"); const warnings = catchWarnings(() => {  warn("Routed warning", "UserWarning", "docs");});console.log(warnings); filterWarnings("error", { category: "ConvergenceWarning" });try {  warn("Did not converge", "ConvergenceWarning");} catch (error) {  console.log(error instanceof DeepboxError); // true}resetWarnings(); console.log(new ShapeError("mismatched shapes") instanceof DeepboxError); // true