Skip to main content
The SDK uses a Result pattern for error handling. All methods return Result<T, E> rather than throwing exceptions.

Result Pattern

const result = await collection.execute()

if (result.error) {
  switch (result.error._tag) {
    case 'NetworkError':
      // Connection issues, timeouts, aborted requests
      console.log(result.error.code) // 'TIMEOUT' | 'CONNECTION_FAILED' | 'ABORTED' | ...
      break
    case 'ApiError':
      // Server errors, rate limits
      console.log(result.error.source) // 'layers' | 'storefront'
      console.log(result.error.status) // HTTP status code
      break
    case 'ValidationError':
      // Invalid parameters
      console.log(result.error.operation) // which method failed
      console.log(result.error.fields) // [{ field, code, message }]
      break
    case 'ConfigError':
      // SDK configuration issues
      console.log(result.error.field) // which config field
      break
  }
} else {
  const data = result.data
}

Error Types

All errors have a _tag property for type discrimination.

NetworkError

Connection failures, timeouts, and aborted requests.
FieldTypeDescription
codeNetworkErrorCodeTIMEOUT, CONNECTION_FAILED, DNS_FAILED, SSL_ERROR, ABORTED, OFFLINE
messagestringHuman-readable description
retryablebooleanWhether the request can be retried
retryAfterMsnumber?Suggested retry delay in milliseconds

ApiError

Server errors, rate limits, and GraphQL errors.
FieldTypeDescription
codeApiErrorCodeNOT_FOUND, RATE_LIMITED, GRAPHQL_ERROR, etc.
sourceApiSource'layers' or 'storefront'
statusnumber?HTTP status code
retryablebooleanWhether the request can be retried
retryAfterMsnumber?Suggested retry delay

ValidationError

Invalid parameters passed to SDK methods.
FieldTypeDescription
operationstringWhich method failed (e.g. 'search')
fieldsValidationFieldError[][{ field, code, message }]

ConfigError

SDK configuration issues at init time.
FieldTypeDescription
fieldstringWhich config field is wrong
expectedstring?What was expected

Error Helpers

The SDK provides utility functions for handling retryable errors:
import { isRetryable, getRetryDelay } from '@commerce-blocks/sdk'

if (result.error && isRetryable(result.error)) {
  const delay = getRetryDelay(result.error) ?? 1000
  setTimeout(() => collection.execute(), delay)
}

Error Handling in Components

When using reactive methods with Preact components, handle errors in your render logic:
function ProductList() {
  const { data, error, isFetching } = collection.state.value

  if (isFetching) {
    return <LoadingSpinner />
  }

  if (error) {
    return <ErrorMessage message="Something went wrong. Please try again." />
  }

  if (!data || data.products.length === 0) {
    return <EmptyState message="No products found." />
  }

  return (
    <div className="product-grid">
      {data.products.map(product => (
        <ProductCard key={product.id} product={product} />
      ))}
    </div>
  )
}