Skip to main content

VIUCraft Documentation

Home Getting Started API Reference Integration Guides Pricing & Plans SDKs Playground URL Builder

JavaScript SDK - Error Handling

On This Page

The SDK provides a structured error hierarchy so you can handle different failure scenarios precisely.

Error Classes

All errors extend the base ViucraftError class:

Code
ViucraftError
├── ViucraftValidationError   — client-side validation failures
├── ViucraftRateLimitError    — HTTP 429 responses
└── ViucraftNetworkError      — connection failures and timeouts

ViucraftError (base)

All SDK errors extend this class.

PropertyTypeDescription
messagestringHuman-readable error description
codestringMachine-readable error code
statusnumber | undefinedHTTP status code (if from API response)
rateLimitRateLimitInfo | undefinedRate limit headers from response
responseDataunknownRaw API response body

ViucraftValidationError

Thrown when a parameter fails client-side validation (no network request is made).

PropertyTypeDescription
parameterNamestringName of the invalid parameter
codestringAlways 'VALIDATION_ERROR'
Typescript
try {
  client.image('img').resize(-1, 100);
} catch (e) {
  if (e instanceof ViucraftValidationError) {
    console.log(e.parameterName); // "width"
    console.log(e.message);       // "width must be a positive integer, got -1"
  }
}

ViucraftRateLimitError

Thrown when the API returns HTTP 429 after all retry attempts are exhausted.

PropertyTypeDescription
retryAfternumber | undefinedSeconds to wait before retrying
rateLimitRateLimitInfo | undefinedRate limit header values
codestringAlways 'RATE_LIMIT_ERROR'
statusnumberAlways 429
Typescript
try {
  await client.uploadImage(buffer);
} catch (e) {
  if (e instanceof ViucraftRateLimitError) {
    console.log(`Rate limited — retry after ${e.retryAfter}s`);
    console.log(`Remaining: ${e.rateLimit?.remaining}`);
  }
}

ViucraftNetworkError

Thrown on connection failures, DNS errors, and timeouts.

PropertyTypeDescription
codestringAlways 'NETWORK_ERROR'
Typescript
try {
  await client.listImages();
} catch (e) {
  if (e instanceof ViucraftNetworkError) {
    console.log('Connection failed:', e.message);
  }
}

Validation Constraints

The SDK validates parameters before building URLs or making requests:

ConstraintAffected ParametersRule
Positive integerwidth, height, sizeMust be > 0 and an integer
Non-negative integerleft, topMust be >= 0 and an integer
Range (0–10)brightness, contrastFactor must be between 0 and 10
Range (1–100)qualityQuality value from 1 to 100
Range (0.01–100)sigma (blur, sharpen)Must be a positive number in range
Range (1–16384)width, height (resize, crop, thumbnail, smartCrop)Max image dimension
Odd integer (1–99)size (median)Must be a positive odd integer
Finite numberangle (rotate)Must be a finite number
Hex colorbackground (rotate)Valid hex like #ff0000 or ff0000
Non-empty stringapiKey, imageIdCannot be empty or whitespace
EnumformatMust be jpg, jpeg, png, or webp
Enumdirection (flip)Must be horizontal, vertical, h, or v
Enumcrop (thumbnail)Must be centre, entropy, or attention
Range (1–∞)page (listImages)Must be >= 1
Range (1–100)limit (listImages)Must be between 1 and 100

Recommended Handling Pattern

Typescript
import {
  ViucraftError,
  ViucraftValidationError,
  ViucraftRateLimitError,
  ViucraftNetworkError,
} from 'viucraft';

try {
  const result = await client.uploadImage(file);
  console.log('Success:', result.image_id);
} catch (error) {
  if (error instanceof ViucraftValidationError) {
    // Bad input — fix the parameter and retry
    console.error(`Invalid ${error.parameterName}: ${error.message}`);
  } else if (error instanceof ViucraftRateLimitError) {
    // Retries exhausted — back off or alert
    console.error(`Rate limited. Retry after ${error.retryAfter}s`);
  } else if (error instanceof ViucraftNetworkError) {
    // Network issue — check connectivity
    console.error('Network error:', error.message);
  } else if (error instanceof ViucraftError) {
    // Other API error (4xx / 5xx)
    console.error(`API error ${error.status}: ${error.message}`);
  } else {
    throw error; // unexpected
  }
}

Retry Configuration

The SDK automatically retries HTTP 429 responses with exponential backoff. Only rate-limit errors are retried — other 4xx/5xx errors fail immediately.

Default Configuration

OptionDefaultDescription
maxRetries3Maximum number of retry attempts
initialDelayMs1000Delay before the first retry (ms)
maxDelayMs30000Maximum delay between retries (ms)
backoffMultiplier2Multiplier applied to delay after each retry

Custom Retry Settings

Typescript
const client = new ViucraftClient({
  apiKey: 'your-key',
  retry: {
    maxRetries: 5,
    initialDelayMs: 500,
    maxDelayMs: 60000,
    backoffMultiplier: 3,
  },
});

Disabling Retries

Typescript
const client = new ViucraftClient({
  apiKey: 'your-key',
  retry: false,
});

Retry Timing

When a 429 is received, the SDK determines the wait time as follows:

  1. If the response includes a Retry-After header, use that value (in seconds).
  2. Otherwise, if X-RateLimit-Reset is present, compute seconds until that Unix timestamp.
  3. Otherwise, use exponential backoff: initialDelayMs * backoffMultiplier ^ attempt, capped at maxDelayMs.

After maxRetries failed attempts, a ViucraftRateLimitError is thrown.

Migration Guide: v1.0 to v1.1

What Changed

v1.1 added the ImageBuilder chainable API, structured error classes, client-side validation, and automatic 429 retry.

Building URLs

Typescript
// v1.0 — still works but deprecated
const url = client.buildImageUrl('img', { resize: { width: 300, height: 200 } });

// v1.1 — preferred chainable API
const url = client.image('img').resize(300, 200).toURL();

Error Handling

Typescript
// v1.0 — generic Axios errors
try { await client.uploadImage(file); }
catch (e) { console.error(e.response?.status); }

// v1.1 — typed SDK errors
try { await client.uploadImage(file); }
catch (e) {
  if (e instanceof ViucraftRateLimitError) {
    // structured access to retryAfter, rateLimit info
  }
}

New Exports

v1.1 adds these exports: ImageBuilder, ViucraftError, ViucraftValidationError, ViucraftRateLimitError, ViucraftNetworkError, and all validation utilities.

Was this helpful?

On This Page