parseJsonResponse static method

Map<String, dynamic> parseJsonResponse(
  1. dynamic responseData, {
  2. String? providerName,
})

Parse HTTP response data to Map<String, dynamic>

Handles different response types:

  • Map<String, dynamic> (direct JSON object)
  • String (JSON string that needs parsing)
  • Other types (error cases)

Implementation

static Map<String, dynamic> parseJsonResponse(
  dynamic responseData, {
  String? providerName,
}) {
  final provider = providerName ?? 'Unknown';

  try {
    // Handle direct JSON object
    if (responseData is Map<String, dynamic>) {
      return responseData;
    }

    // Handle JSON string
    if (responseData is String) {
      // Check if it's HTML (common error case)
      if (responseData.trim().startsWith('<')) {
        _logger.severe('$provider API returned HTML instead of JSON');
        throw ResponseFormatError(
          '$provider API returned HTML page instead of JSON response. '
          'This usually indicates an incorrect API endpoint or authentication issue.',
          responseData.length > 500
              ? '${responseData.substring(0, 500)}...'
              : responseData,
        );
      }

      // Try to parse as JSON
      try {
        final jsonData = jsonDecode(responseData);
        if (jsonData is Map<String, dynamic>) {
          return jsonData;
        } else {
          throw ResponseFormatError(
            '$provider API returned JSON that is not an object',
            responseData.length > 500
                ? '${responseData.substring(0, 500)}...'
                : responseData,
          );
        }
      } on FormatException catch (e) {
        _logger.severe('$provider API returned invalid JSON: ${e.message}');
        throw ResponseFormatError(
          '$provider API returned invalid JSON: ${e.message}',
          responseData.length > 500
              ? '${responseData.substring(0, 500)}...'
              : responseData,
        );
      }
    }

    // Handle other types
    throw ResponseFormatError(
      '$provider API returned unexpected response type: ${responseData.runtimeType}',
      responseData.toString().length > 500
          ? '${responseData.toString().substring(0, 500)}...'
          : responseData.toString(),
    );
  } catch (e) {
    if (e is LLMError) {
      rethrow;
    }
    _logger.severe('Unexpected error parsing $provider response: $e');
    throw GenericError('Failed to parse $provider API response: $e');
  }
}