Skip to content

Commit 6372e2b

Browse files
committed
Enhance cache retrieval methods to handle exceptions and improve expiration checks
1 parent 8f786ba commit 6372e2b

File tree

2 files changed

+37
-14
lines changed

2 files changed

+37
-14
lines changed

src/LocalStorage/LocalStorageAsyncExtensions .cs

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ public static class LocalStorageAsyncExtensions
1212
{
1313
var (isCacheExist, cache) = await localStorageService.TryGetCacheAsync<T>(key);
1414
if (isCacheExist) return cache;
15-
15+
1616
try
1717
{
1818
var newData = await generateCache();
@@ -27,15 +27,29 @@ public static class LocalStorageAsyncExtensions
2727
}
2828

2929
public static async ValueTask<(bool isCacheExist, T? cacheItem)> TryGetCacheAsync<T>(
30-
this ILocalStorageService localStorageService,
31-
string key)
30+
this ILocalStorageService localStorageService,
31+
string key)
3232
{
3333
ArgumentNullException.ThrowIfNullOrWhiteSpace(key);
3434

35-
var cache = await localStorageService.GetItemAsync<LocalCacheItem<T>>(key);
36-
return cache is { } existingCache && !existingCache.IsExpired()
37-
? (true, existingCache.Data)
38-
: (false, default);
35+
try
36+
{
37+
var cache = await localStorageService.GetItemAsync<LocalCacheItem<T>>(key);
38+
39+
if (cache is null) return (false, default);
40+
41+
Console.WriteLine($"Cache retrieved for {key}. Expires at: {cache.ExpiresAt}. IsExpired: {cache.IsExpired()}");
42+
43+
return cache.IsExpired()
44+
? (false, default)
45+
: (true, cache.Data);
46+
}
47+
catch (Exception)
48+
{
49+
// Remove cache if anything happened
50+
await localStorageService.RemoveItemAsync(key);
51+
return (false, default);
52+
}
3953
}
4054

4155
}

src/LocalStorage/LocalStorageSyncExtensions.cs

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,16 +33,25 @@ public static bool TryGetCache<T>(
3333
out T? cacheData)
3434
{
3535
ArgumentNullException.ThrowIfNullOrWhiteSpace(key);
36+
try
37+
{
38+
var currentCache = localStorageService.GetItem<LocalCacheItem<T>>(key);
3639

37-
var currentCache = localStorageService.GetItem<LocalCacheItem<T>>(key);
40+
if (currentCache is { } existingCache && !existingCache.IsExpired())
41+
{
42+
cacheData = existingCache.Data;
43+
return true;
44+
}
3845

39-
if (currentCache is { } existingCache && !existingCache.IsExpired())
46+
cacheData = default;
47+
return false;
48+
}
49+
catch (Exception)
4050
{
41-
cacheData = existingCache.Data;
42-
return true;
51+
// Remove cache if anything happened
52+
localStorageService.RemoveItem(key);
53+
cacheData = default;
54+
return false;
4355
}
44-
45-
cacheData = default;
46-
return false;
4756
}
4857
}

0 commit comments

Comments
 (0)