From 04d00e0fe9b6f03bfe28224d9e92639a0ea0e321 Mon Sep 17 00:00:00 2001 From: Jeff Leung Date: Fri, 5 Jan 2024 16:35:24 -0800 Subject: [PATCH] Handle errors --- .../Controllers/GeofeedController.cs | 45 +++++++++++-------- 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/AS1024.GeoFeed/Controllers/GeofeedController.cs b/AS1024.GeoFeed/Controllers/GeofeedController.cs index 8f03a9b..a0c3fa0 100644 --- a/AS1024.GeoFeed/Controllers/GeofeedController.cs +++ b/AS1024.GeoFeed/Controllers/GeofeedController.cs @@ -16,11 +16,14 @@ namespace AS1024.GeoFeed.Controllers private readonly IGeoFeedProvider builder; private readonly IMemoryCache memoryCache; private readonly IWebHostEnvironment environment; + private readonly ILogger logger; private const string GeoFeedCacheKey = "GeoFeedData"; public GeofeedController(IGeoFeedProvider builder, IMemoryCache memoryCache, - IWebHostEnvironment environment) { + IWebHostEnvironment environment, + ILogger logger) { + this.logger = logger; this.builder = builder; this.memoryCache = memoryCache; this.environment = environment; @@ -30,26 +33,32 @@ namespace AS1024.GeoFeed.Controllers [Route("")] public async Task Get() { - if (!memoryCache.TryGetValue(GeoFeedCacheKey, out List? feed) - && environment.IsProduction()) + try { - feed = await builder.GetGeoFeedData(); - MemoryCacheEntryOptions cacheEntryOptions = new MemoryCacheEntryOptions() - .SetSlidingExpiration(TimeSpan.FromMinutes(15)); - memoryCache.Set(GeoFeedCacheKey, feed, cacheEntryOptions); - } else + if (!memoryCache.TryGetValue(GeoFeedCacheKey, out List? feed)) + { + feed = await builder.GetGeoFeedData(); + if (environment.IsProduction()) + { + MemoryCacheEntryOptions cacheEntryOptions = new MemoryCacheEntryOptions() + .SetSlidingExpiration(TimeSpan.FromMinutes(15)); + memoryCache.Set(GeoFeedCacheKey, feed, cacheEntryOptions); + } + } + + string csvContent = feed.ToGeoFeedCsv(); // Assuming ToGeoFeedCsv() returns a string in CSV format. + byte[] contentBytes = Encoding.UTF8.GetBytes(csvContent); + string contentType = "text/csv"; + + return new FileContentResult(contentBytes, contentType) + { + FileDownloadName = "geofeed.csv" + }; + } catch (Exception ex) { - feed = await builder.GetGeoFeedData(); + logger.LogError($"Geofeed generation failed. Exception: {ex}"); + return StatusCode(500); } - - string csvContent = feed.ToGeoFeedCsv(); // Assuming ToGeoFeedCsv() returns a string in CSV format. - byte[] contentBytes = Encoding.UTF8.GetBytes(csvContent); - string contentType = "text/csv"; - - return new FileContentResult(contentBytes, contentType) - { - FileDownloadName = "geofeed.csv" - }; } } }