# API Error Handling Utilities

This module provides utilities for handling API errors consistently across the application.

## Functions

### `extractErrorMessage(err: unknown): string`

Extracts meaningful error messages from API exceptions and other errors.

**Parameters:**
- `err` - The error object caught from API calls

**Returns:**
- A user-friendly error message string

**Usage:**
```typescript
import { extractErrorMessage } from '../utils/apiErrorHandler'

try {
  const result = await apiCall()
} catch (err) {
  const errorMessage = extractErrorMessage(err)
  console.log(errorMessage) // "Insufficient balance for swap"
}
```

### `handleApiError(err: unknown)`

Handles API errors and returns a standardized error object with additional context.

**Parameters:**
- `err` - The error object caught from API calls

**Returns:**
```typescript
{
  message: string
  isApiException: boolean
  status?: number
  response?: string
}
```

**Usage:**
```typescript
import { handleApiError } from '../utils/apiErrorHandler'

try {
  const result = await apiCall()
} catch (err) {
  const errorInfo = handleApiError(err)
  console.log(errorInfo.message) // "Insufficient balance for swap"
  console.log(errorInfo.status) // 400
  console.log(errorInfo.isApiException) // true
}
```

## Custom Hook

### `useApiError()`

A React hook that provides error handling utilities for API calls.

**Returns:**
```typescript
{
  error: string | null
  setError: (error: string | null) => void
  clearError: () => void
  handleError: (err: unknown) => string
  handleApiErrorWithToast: (err: unknown, toast: any) => void
}
```

**Usage:**
```typescript
import { useApiError } from '../hooks/useApiError'

function MyComponent() {
  const { error, setError, clearError, handleError, handleApiErrorWithToast } = useApiError()
  
  const handleApiCall = async () => {
    try {
      const result = await apiCall()
      clearError() // Clear any previous errors
    } catch (err) {
      // Option 1: Simple error handling
      const errorMessage = handleError(err)
      
      // Option 2: Error handling with toast
      handleApiErrorWithToast(err, toast)
    }
  }
  
  return (
    <div>
      {error && <div className="alert alert-error">{error}</div>}
      <button onClick={handleApiCall}>Make API Call</button>
    </div>
  )
}
```

## Error Types Handled

1. **ApiException** - Generated client exceptions with server response details
2. **Error** - Standard JavaScript Error objects
3. **Unknown** - Any other error types

## Response Parsing

The utilities attempt to parse JSON responses in this order:
1. `message` - Standard error message field
2. `error` - Alternative error field
3. `detail` - ASP.NET Core validation error field
4. Raw response text if JSON parsing fails
5. Exception message as final fallback

## Examples

### Basic Usage
```typescript
try {
  const result = await client.someApiCall()
} catch (err) {
  const errorMessage = extractErrorMessage(err)
  setError(errorMessage)
}
```

### With Toast Notifications
```typescript
const { handleApiErrorWithToast } = useApiError()

try {
  const result = await client.someApiCall()
  toast.update('success', 'Operation successful!')
} catch (err) {
  handleApiErrorWithToast(err, toast)
}
```

### With Custom Error Handling
```typescript
const { handleError } = useApiError()

try {
  const result = await client.someApiCall()
} catch (err) {
  const errorMessage = handleError(err)
  
  // Custom logic based on error type
  if (errorMessage.includes('insufficient')) {
    showBalanceWarning()
  } else if (errorMessage.includes('network')) {
    showRetryButton()
  }
}
``` 