diff --git a/Elecciones-Web/src/Elecciones.Infrastructure/Services/ElectoralApiService.cs b/Elecciones-Web/src/Elecciones.Infrastructure/Services/ElectoralApiService.cs index 582c3c4..2664d76 100644 --- a/Elecciones-Web/src/Elecciones.Infrastructure/Services/ElectoralApiService.cs +++ b/Elecciones-Web/src/Elecciones.Infrastructure/Services/ElectoralApiService.cs @@ -3,6 +3,8 @@ using Microsoft.Extensions.Configuration; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.Extensions.Logging; using System.Threading.Tasks; using static Elecciones.Core.DTOs.BancaDto; @@ -12,11 +14,15 @@ public class ElectoralApiService : IElectoralApiService { private readonly IHttpClientFactory _httpClientFactory; private readonly IConfiguration _configuration; + private readonly ILogger _logger; - public ElectoralApiService(IHttpClientFactory httpClientFactory, IConfiguration configuration) + public ElectoralApiService(IHttpClientFactory httpClientFactory, + IConfiguration configuration, + ILogger logger) { _httpClientFactory = httpClientFactory; _configuration = configuration; + _logger = logger; } public async Task GetAuthTokenAsync() @@ -113,8 +119,39 @@ public class ElectoralApiService : IElectoralApiService var requestUri = $"/api/resultados/getFile?mesaId={mesaId}"; 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) + { + _logger.LogError(ex, "La petición HTTP a getFile falló para la mesa {mesaId}", mesaId); + return null; + } + + if (response.IsSuccessStatusCode && response.Content?.Headers.ContentLength > 0) + { + try + { + return await response.Content.ReadFromJsonAsync(); + } + catch (JsonException ex) + { + // Si la deserialización falla, ahora lo sabremos exactamente. + _logger.LogWarning(ex, "La API devolvió una respuesta no-JSON para la mesa {mesaId}. Status: {statusCode}", mesaId, response.StatusCode); + return null; + } + } + else if (!response.IsSuccessStatusCode) + { + _logger.LogWarning("La API devolvió un código de error {statusCode} para la mesa {mesaId}", response.StatusCode, mesaId); + } + // Si la respuesta fue exitosa pero sin contenido, no es necesario loguearlo como un error, + // simplemente devolvemos null y el Worker lo ignorará. + + return null; } public async Task GetResumenAsync(string authToken, string distritoId)