# Error Handling

The SDK emits errors as events and (when applicable) throws a custom `SDKError`. Your app should handle both.

## SDKError

All SDK errors use a custom error class:

```typescript
class SDKError extends Error {
  constructor(message: string, reThrow?: boolean);
  name: 'SDKError';
  isSdk: boolean;
  reThrow: boolean;
}
```

## Catching Errors

```javascript
try {
  // Structural input errors throw a catchable SDKError — e.g. a non-array
  // argument or an empty array:
  await window.LiquidCommerce.elements.injectProductElement([]);
} catch (error) {
  if (error.name === 'SDKError') {
    console.error('SDK Error:', error);
  }
}
```

> A well-formed entry with an invalid product identifier does **not** throw — it renders an error view inside the component and sets an error in the store. `try/catch` here only catches structural input errors (a non-array argument or an empty array).

## Error Isolation

Component failures are contained — a component that fails to load renders an error view and logs to the console without crashing your page. Action methods (like `cart.addProduct`) emit a `*_FAILED` event on failure, and re-throw only on an unexpected error; several soft-failure paths (e.g. no product found, no items added) emit the failure event but still resolve. Wrap calls in try/catch **and** listen for the corresponding `*_failed` event to reliably detect failures:

```javascript
try {
  await window.LiquidCommerce.elements.actions.cart.addProduct([/* invalid */]);
} catch (error) {
  console.log('Handled add-to-cart failure');
}
```

## Error Events

Listen for failure events to show user-friendly messages or trigger retries:

```javascript
// Cart add failed
window.addEventListener('lce:actions.cart_product_add_failed', (event) => {
  console.error('Failed to add:', event.detail.data.error);
});

// Address failed
window.addEventListener('lce:actions.address_failed', (event) => {
  console.error('Address error:', event.detail.data.error);
});

// Checkout submit failed
window.addEventListener('lce:actions.checkout_submit_failed', (event) => {
  console.error('Checkout failed:', event.detail.data.message);
});
```

## UI Errors

When a component fails to load, the SDK renders an error view inside the container and logs details to the console.

## Related Docs

- [Events Guide](../guides/events.md)
- [Client API](../api/client.md)
- [Troubleshooting](./troubleshooting.md)
