# Error Handling

Handle API errors gracefully in your application.

**Response Codes:**
| Status | Description |
|--------|-------------|
| 200/201 | Request successful |
| 400 | Validation error (check parameters) |
| 401 | Unauthorized (invalid API key) |
| 404 | Content not found |
| 500 | Internal server error |

**Error Handling Patterns**

_Swift (iOS)_
```swift
// Comprehensive error handling with Swift SDK
Task {
    let result = await kinestex.fetchWorkouts(category: "Fitness", limit: 10)

    switch result {
    case .success(let response):
        // Handle successful response
        let workouts = response.workouts
        print("Success: Fetched \(workouts.count) workouts")

    case .failure(let error):
        // Handle different error types
        if let urlError = error as? URLError {
            switch urlError.code {
            case .notConnectedToInternet:
                print("No internet connection")
            case .timedOut:
                print("Request timed out")
            default:
                print("Network error: \(urlError.localizedDescription)")
            }
        } else {
            print("Error: \(error.localizedDescription)")
        }
    }
}

// Using fetchContent for advanced error handling
Task {
    let result = await kinestex.fetchContent(
        contentType: .workout,
        id: "invalid_id"
    )

    switch result {
    case .workout(let workout):
        print("Found: \(workout.title)")

    case .error(let message):
        // API returned an error message
        print("API Error: \(message)")

    case .rawData(let data, let errorMessage):
        // Parsing failed, but raw data is available
        print("Parse error: \(errorMessage ?? "Unknown")")
        print("Raw data: \(data)")

    default:
        print("Unexpected result type")
    }
}
```

_Kotlin (Android)_
```kotlin
// Comprehensive error handling with Kotlin SDK
lifecycleScope.launch {
    try {
        val result = withContext(Dispatchers.IO) {
            KinesteXSDK.api.fetchAPIContentData(
                contentType = ContentType.WORKOUT,
                category = "Fitness",
                limit = 10
            )
        }

        when (result) {
            is APIContentResult.Workouts -> {
                // Handle successful response
                val workouts = result.workouts
                Log.d("API", "Success: Fetched ${workouts.size} workouts")
            }
            is APIContentResult.Error -> {
                // API returned an error
                Log.e("API", "API Error: ${result.message}")

                // Show user-friendly message
                Toast.makeText(
                    this@MainActivity,
                    "Failed to load workouts: ${result.message}",
                    Toast.LENGTH_LONG
                ).show()
            }
            else -> {
                Log.w("API", "Unexpected result type")
            }
        }
    } catch (e: Exception) {
        // Handle network or other exceptions
        Log.e("API", "Exception: ${e.message}")

        when (e) {
            is java.net.UnknownHostException -> {
                Toast.makeText(this@MainActivity, "No internet connection", Toast.LENGTH_SHORT).show()
            }
            is java.net.SocketTimeoutException -> {
                Toast.makeText(this@MainActivity, "Request timed out", Toast.LENGTH_SHORT).show()
            }
            else -> {
                Toast.makeText(this@MainActivity, "Error: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
```

_Flutter_
```dart
// Comprehensive error handling with Flutter SDK
Future<void> fetchWithErrorHandling() async {
  try {
    final result = await KinesteXAIFramework.apiService.fetchContent(
      contentType: ContentType.workout,
      category: "Fitness",
      limit: 10,
    );

    switch (result) {
      case WorkoutsResult(:final response):
        // Handle successful response
        print('Success: Fetched ${response.workouts.length} workouts');

      case ErrorResult(:final message):
        // API returned an error
        print('API Error: $message');

        // Show user-friendly message
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to load workouts: $message')),
        );

      case RawDataResult(:final data, :final errorMessage):
        // Parsing failed, but raw data is available
        print('Parse error: ${errorMessage ?? "Unknown"}');
        print('Raw data keys: ${data.keys}');

      default:
        print('Unexpected result type');
    }
  } on SocketException {
    // No internet connection
    print('No internet connection');
  } on TimeoutException {
    // Request timed out
    print('Request timed out');
  } catch (e) {
    // Other errors
    print('Error: $e');
  }
}
```

_React Native_
```jsx
// Comprehensive error handling with fetch API
const fetchWithErrorHandling = async (): Promise<WorkoutModel[]> => {
  try {
    const response = await fetch(
      `${BASE_URL}/workouts?category=Fitness&limit=10`,
      { headers }
    );

    if (!response.ok) {
      // Handle HTTP errors
      switch (response.status) {
        case 400:
          throw new Error('Invalid request parameters');
        case 401:
          throw new Error('Invalid API key');
        case 404:
          throw new Error('Content not found');
        case 500:
          throw new Error('Server error - please try again later');
        default:
          throw new Error(`HTTP Error: ${response.status}`);
      }
    }

    const data = await response.json();

    // Check for API-level errors
    if (data.error) {
      throw new Error(data.error);
    }

    return data.workouts;

  } catch (error) {
    if (error instanceof TypeError && error.message === 'Network request failed') {
      // No internet connection
      console.error('No internet connection');
      throw new Error('Please check your internet connection');
    }

    // Re-throw the error
    throw error;
  }
};

// Usage with error handling
try {
  const workouts = await fetchWithErrorHandling();
  console.log(`Fetched ${workouts.length} workouts`);
} catch (error) {
  Alert.alert('Error', error.message);
}
```

_HTML / JavaScript_
```html
// Comprehensive error handling with fetch API
async function fetchWithErrorHandling() {
  try {
    const response = await fetch(
      `${BASE_URL}/workouts?category=Fitness&limit=10`,
      { headers }
    );

    if (!response.ok) {
      // Handle HTTP errors
      switch (response.status) {
        case 400:
          throw new Error('Invalid request parameters');
        case 401:
          throw new Error('Invalid API key');
        case 404:
          throw new Error('Content not found');
        case 500:
          throw new Error('Server error - please try again later');
        default:
          throw new Error(`HTTP Error: ${response.status}`);
      }
    }

    const data = await response.json();

    // Check for API-level errors
    if (data.error) {
      throw new Error(data.error);
    }

    return data.workouts;

  } catch (error) {
    if (error instanceof TypeError && error.message === 'Failed to fetch') {
      // No internet connection or CORS error
      console.error('Network error');
      throw new Error('Please check your internet connection');
    }

    // Re-throw the error
    throw error;
  }
}

// Usage with error handling
fetchWithErrorHandling()
  .then(workouts => console.log(`Fetched ${workouts.length} workouts`))
  .catch(error => alert(`Error: ${error.message}`));
```

_React (TypeScript)_
```tsx
// Comprehensive error handling with TypeScript
class APIError extends Error {
  constructor(
    message: string,
    public statusCode?: number,
    public originalError?: unknown
  ) {
    super(message);
    this.name = 'APIError';
  }
}

const fetchWithErrorHandling = async (): Promise<WorkoutModel[]> => {
  try {
    const response = await fetch(
      `${BASE_URL}/workouts?category=Fitness&limit=10`,
      { headers }
    );

    if (!response.ok) {
      // Handle HTTP errors
      const errorMessages: Record<number, string> = {
        400: 'Invalid request parameters',
        401: 'Invalid API key',
        404: 'Content not found',
        500: 'Server error - please try again later',
      };

      throw new APIError(
        errorMessages[response.status] || `HTTP Error: ${response.status}`,
        response.status
      );
    }

    const data = await response.json();

    // Check for API-level errors
    if (data.error) {
      throw new APIError(data.error);
    }

    return data.workouts;

  } catch (error) {
    if (error instanceof APIError) {
      throw error;
    }

    if (error instanceof TypeError) {
      throw new APIError('Please check your internet connection', undefined, error);
    }

    throw new APIError('An unexpected error occurred', undefined, error);
  }
};

// Usage with error handling
try {
  const workouts = await fetchWithErrorHandling();
  console.log(`Fetched ${workouts.length} workouts`);
} catch (error) {
  if (error instanceof APIError) {
    console.error(`API Error (${error.statusCode}): ${error.message}`);
  }
}
```

---
Source: https://kinestex.com/docs/content-api/content-api-errors · Index: https://kinestex.com/llms.txt
