@uturi/sonification

Error Handling

Handle failures with SonificationError and structured ERROR_CODES.

Every error thrown by the library is a SonificationError, with a code plus an optional field name and cause.

SonificationError

class SonificationError extends Error {
  readonly code: SonificationErrorCode;
  readonly cause?: Error;
  readonly field?: string;
}

Error codes

export const ERROR_CODES = {
  WORKER_ERROR: 'WORKER_ERROR', // Web Worker initialization or execution error
  VALIDATION_ERROR: 'VALIDATION_ERROR', // Input data or configuration validation failed
  TIMEOUT_ERROR: 'TIMEOUT_ERROR', // Audio generation timeout
  AUDIO_CONTEXT_ERROR: 'AUDIO_CONTEXT_ERROR', // AudioContext related error
  UNKNOWN_ERROR: 'UNKNOWN_ERROR', // Unknown error
} as const;

Basic handling

import { Sonifier, SonificationError, ERROR_CODES } from '@uturi/sonification';

const sonifier = new Sonifier();

try {
  const result = await sonifier.sonify(data, 'melody', { autoPlay: true });
  console.log('Success:', result);
} catch (error) {
  if (error instanceof SonificationError) {
    switch (error.code) {
      case ERROR_CODES.VALIDATION_ERROR:
        console.error('Validation error:', error.message);
        console.error('Field:', error.field);
        break;
      case ERROR_CODES.WORKER_ERROR:
        console.error('Worker error:', error.message);
        if (error.cause) console.error('Cause:', error.cause);
        break;
      case ERROR_CODES.TIMEOUT_ERROR:
        console.error('Timeout error:', error.message);
        break;
      case ERROR_CODES.AUDIO_CONTEXT_ERROR:
        console.error('AudioContext error:', error.message);
        break;
      default:
        console.error('Unknown error:', error.message);
    }
  }
}

Validation examples

try {
  sonifier.setConfig({
    minFrequency: 1000,
    maxFrequency: 500, // invalid: min > max
  });
} catch (error) {
  if (error instanceof SonificationError && error.code === ERROR_CODES.VALIDATION_ERROR) {
    console.error('Validation failed:', error.message);
    console.error('Problem field:', error.field); // 'frequency'
  }
}

Framework hooks

In hooks, error is SonificationError | null (or a reactive wrapper of that type):

import { useSonifier } from '@uturi/sonification/react';
import { ERROR_CODES } from '@uturi/sonification';

function MyComponent() {
  const { sonify, error } = useSonifier();

  if (error?.code === ERROR_CODES.VALIDATION_ERROR) {
    return <div>Validation error: {error.message}</div>;
  }

  // ...
}

On this page