From 80a9855acd79e6879978217bc721048fa2ac2126 Mon Sep 17 00:00:00 2001 From: dmolinari Date: Tue, 19 Aug 2025 18:33:54 -0300 Subject: [PATCH] Fix getBancas --- .../Services/ElectoralApiService.cs | 39 +++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/Elecciones-Web/src/Elecciones.Infrastructure/Services/ElectoralApiService.cs b/Elecciones-Web/src/Elecciones.Infrastructure/Services/ElectoralApiService.cs index 2664d76..db39b88 100644 --- a/Elecciones-Web/src/Elecciones.Infrastructure/Services/ElectoralApiService.cs +++ b/Elecciones-Web/src/Elecciones.Infrastructure/Services/ElectoralApiService.cs @@ -83,7 +83,6 @@ public class ElectoralApiService : IElectoralApiService var client = _httpClientFactory.CreateClient("ElectoralApiClient"); var requestUri = $"/api/resultados/getBancas?distritoId={distritoId}&categoriaId={categoriaId}"; - // Añadimos el seccionProvincialId a la URL SÓLO si tiene un valor. if (!string.IsNullOrEmpty(seccionProvincialId)) { requestUri += $"&seccionProvincialId={seccionProvincialId}"; @@ -91,8 +90,42 @@ public class ElectoralApiService : IElectoralApiService var request = new HttpRequestMessage(HttpMethod.Get, requestUri); request.Headers.Add("Authorization", $"Bearer {authToken}"); - var response = await client.SendAsync(request); - return response.IsSuccessStatusCode ? await response.Content.ReadFromJsonAsync() : null; + + HttpResponseMessage response; + try + { + response = await client.SendAsync(request); + } + catch (Exception ex) + { + // Captura errores de red (ej. la API se cae momentáneamente) + _logger.LogError(ex, "La petición HTTP a getBancas falló. URI: {requestUri}", requestUri); + return null; + } + + // Comprobamos que la respuesta fue exitosa Y que contiene datos antes de intentar leerla. + if (response.IsSuccessStatusCode && response.Content?.Headers.ContentLength > 0) + { + try + { + // Solo si hay contenido, intentamos deserializar. + return await response.Content.ReadFromJsonAsync(); + } + catch (JsonException ex) + { + // Si el contenido no es un JSON válido, lo registramos y devolvemos null. + _logger.LogWarning(ex, "La API devolvió una respuesta no-JSON para getBancas. URI: {requestUri}, Status: {statusCode}", requestUri, response.StatusCode); + return null; + } + } + else if (!response.IsSuccessStatusCode) + { + // Si la API devolvió un error HTTP, lo registramos. + _logger.LogWarning("La API devolvió un código de error {statusCode} para getBancas. URI: {requestUri}", response.StatusCode, requestUri); + } + + // Si la respuesta fue 200 OK pero con cuerpo vacío, o si fue un error HTTP, devolvemos null. + return null; } public async Task?> GetTelegramasTotalizadosAsync(string authToken, string distritoId, string seccionId, int? categoriaId = null)