Handle errors

This commit is contained in:
Jeff Leung 2024-01-05 16:35:24 -08:00
parent 8a18e71a6f
commit 04d00e0fe9
1 changed files with 27 additions and 18 deletions

View File

@ -16,11 +16,14 @@ namespace AS1024.GeoFeed.Controllers
private readonly IGeoFeedProvider builder;
private readonly IMemoryCache memoryCache;
private readonly IWebHostEnvironment environment;
private readonly ILogger<GeofeedController> logger;
private const string GeoFeedCacheKey = "GeoFeedData";
public GeofeedController(IGeoFeedProvider builder,
IMemoryCache memoryCache,
IWebHostEnvironment environment) {
IWebHostEnvironment environment,
ILogger<GeofeedController> 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<IActionResult> Get()
{
if (!memoryCache.TryGetValue(GeoFeedCacheKey, out List<IPGeoFeed>? 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<IPGeoFeed>? 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"
};
}
}
}