Carta Clara: carta QR, administración y lectura de fotos con Gemini
Una carta QR con panel por restaurante y lectura de fotos mediante Gemini. Código abierto, edición manual y revisión antes de incorporar platos.
Aprende a manejar errores en servicios de IA con .NET: fallos de red, timeouts, rate limiting 429, validación de respuestas y patrones de retry con Polly.

Las aplicaciones de IA enfrentan errores únicos: rate limits, timeouts, respuestas inesperadas del modelo, y fallos de red. Este tutorial cubre estrategias robustas de manejo de errores para aplicaciones de IA en producción.
try
{
var response = await aiService.GenerateAsync(prompt);
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "Error de conexión al servicio de IA");
// Retry o fallback
}
catch (TaskCanceledException ex)
{
_logger.LogError(ex, "Timeout al llamar al servicio de IA");
// Timeout handling
}
catch (RequestFailedException ex) when (ex.Status == 429)
{
var retryAfter = ex.GetRawResponse()?.Headers
.TryGetValue("Retry-After", out var value) == true
? int.Parse(value) : 60;
_logger.LogWarning("Rate limit alcanzado. Reintentar en {Seconds}s", retryAfter);
await Task.Delay(TimeSpan.FromSeconds(retryAfter));
// Retry
}
var response = await aiService.GenerateAsync(prompt);
if (string.IsNullOrWhiteSpace(response))
{
throw new AIServiceException("Modelo retornó respuesta vacía");
}
if (!IsValidFormat(response))
{
_logger.LogWarning("Respuesta en formato inesperado: {Response}", response);
// Intentar parsear o usar respuesta por defecto
}
public async Task<string> GenerateWithRetryAsync(
string prompt,
int maxRetries = 3)
{
for (int attempt = 0; attempt < maxRetries; attempt++)
{
try
{
return await _aiService.GenerateAsync(prompt);
}
catch (Exception ex) when (attempt < maxRetries - 1)
{
_logger.LogWarning(ex, "Intento {Attempt} falló, reintentando...", attempt + 1);
await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)));
}
}
throw new AIServiceException(
quot;Fallo después de {maxRetries} intentos"); }
using Polly;
var retryPolicy = Policy
.Handle<HttpRequestException>()
.Or<RequestFailedException>(ex => ex.Status == 429 || ex.Status == 503)
.WaitAndRetryAsync(
retryCount: 3,
sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)),
onRetry: (exception, timeSpan, retryCount, context) =>
{
_logger.LogWarning(
"Retry {RetryCount} después de {Delay}s: {Error}",
retryCount, timeSpan.TotalSeconds, exception.Message);
});
var response = await retryPolicy.ExecuteAsync(
async () => await _aiService.GenerateAsync(prompt));
Palabras clave: error handling, retry patterns, Polly, resilience, exception handling, AI services