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
DeepboxErrordirectly, and no class extends another.instanceof ShapeErrortherefore does not match aBroadcastError. Catch the specific class, orDeepboxErrorto catch them all. - Shape mismatches in tensor operations throw
ShapeError.BroadcastErroris exported for your own code, but the library reports failed broadcasts asShapeError. Mixed devices, a missing backend, an operation a device does not support and a disposed tensor throwDeviceError. warn(message, category, source)sends a warning to the handler set withsetWarningHandler, or toconsole.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 emitConvergenceWarningorUserWarning.Logger(verbose, source)takes a level from 0 (silent) to 3 (trace) and prints throughconsole.log, or through the handler set withsetLogHandler. The library does not log through it. It is a utility for your own code.
ConvergenceErrorDetails
typeDetails for convergence failures.
readonly iterations?: numberreadonly tolerance?: numberreadonly cause?: unknown
ShapeErrorDetails
typeDetails about a shape mismatch error.
readonly expected?: Shapereadonly received?: Shapereadonly context?: stringreadonly cause?: unknown
LogEntry
interfaceA log entry produced by the logger.
readonly level: VerboseLevelreadonly message: stringreadonly timestamp: numberMilliseconds since the Unix epoch, from
Date.now().readonly source?: stringName of the component that produced the entry (the Logger's
source).
VerboseLevel
typeVerbosity level type (0 = silent, higher = more verbose).
type VerboseLevel = 0 | 1 | 2 | 3;DeepboxWarning
interfaceStructured warning emitted by Deepbox components.
category: WarningCategorymessage: stringsource?: string | undefined
WarningAction
typeAction 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
typeCategory of a Deepbox warning, mirroring scikit-learn's warning categories.
type WarningCategory = "ConvergenceWarning" | "DataConversionWarning" | "UndefinedMetricWarning" | "FitFailedWarning" | "UserWarning";BroadcastError
extends DeepboxErrorError 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.
// 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: stringreadonly shape1: ShapeThe first shape involved in the broadcast operation
readonly shape2: ShapeThe second shape involved in the broadcast operation
ConvergenceError
extends DeepboxErrorError 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.
if (iterations >= maxIterations) { throw new ConvergenceError( `Algorithm did not converge after ${maxIterations} iterations` );}Members (4)
constructor(message: string, details?: ConvergenceErrorDetails)name: stringreadonly iterations?: numberNumber of iterations completed before convergence failure
readonly tolerance?: numberTolerance value used for convergence check
DataValidationError
extends DeepboxErrorError thrown when data validation fails.
Used for input data that doesn't meet expected format or constraints.
if (!Array.isArray(data)) { throw new DataValidationError('Expected array input');}Members (1)
name: string
DeepboxError
extends ErrorBase 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 DeepboxErrorError 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: stringDiscriminator name for this error type.
DTypeError
extends DeepboxErrorError 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: stringDiscriminator name for this error type.
IndexError
extends DeepboxErrorError thrown when an invalid index is used to access tensor elements.
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: stringreadonly index?: numberThe invalid index value
readonly validRange?: readonly [ number, number ]The valid range for the index
InvalidParameterError
extends DeepboxErrorError thrown when invalid parameters are passed to a function or method.
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: stringreadonly parameterName?: stringThe name of the invalid parameter
readonly value?: unknownThe invalid value that was provided
MemoryError
extends DeepboxErrorError thrown when memory allocation fails or memory limits are exceeded.
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: stringreadonly requestedBytes?: numberThe amount of memory requested in bytes
readonly availableBytes?: numberThe amount of memory available in bytes
NotFittedError
extends DeepboxErrorError thrown when a model or estimator is used before being fitted.
Thrown when a model is used before calling fit().
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: stringreadonly modelName?: stringThe name of the model or estimator that was not fitted
NotImplementedError
extends DeepboxErrorError 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: stringDiscriminator name for this error type.
ShapeError
extends DeepboxErrorError 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.
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: stringreadonly expected: Shape | undefinedreadonly received: Shape | undefinedreadonly context: string | undefinedstatic mismatch(expected: Shape, received: Shape, context?: string): ShapeErrorCreate a ShapeError for a shape mismatch.
Logger
Logger for Deepbox models and utilities.
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 >= 3Members (8)
constructor(verbose: VerboseLevel, source: string)level: VerboseLevelThe configured verbosity level.
info(message: string): voidLog at level 1 (summary).
debug(message: string): voidLog at level 2 (per-iteration progress).
trace(message: string): voidLog at level 3 (trace/debug detail).
log(level: VerboseLevel, message: string): voidLog a message at a specific level.
getEntries(): readonly LogEntry[]Get the recorded log entries in chronological order (regardless of verbosity).
clear(): voidClear all recorded entries.
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
handlerLogHandler | 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
actionWarningAction- 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
InvalidParameterErrorIfactionis 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
handlerWarningHandler | 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
messagestring- Warning message
categoryoptionalWarningCategory- Warning category (default: "UserWarning")
sourceoptionalstring- Optional source identifier (e.g. function name)
Throws
DeepboxErrorIf a matching filter has the"error"action
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); // trueFound a mistake? Open an issue.