Solution: Shipping API Timeout Fallback

Review how to use WaitAsync and exception handling to implement an asynchronous timeout fallback pattern inside a service class.

Solution: Shipping API Timeout Fallback

Review how to use WaitAsync and exception handling to implement an asynchronous timeout fallback pattern inside a service class.
C# 14.0
using System.Threading.Tasks;
namespace Logistics;
public class ShippingCalculator
{
public async Task<string> GetRateWithFallbackAsync()
{
try
{
string liveRate = await GetLiveShippingRateAsync().WaitAsync(TimeSpan.FromSeconds(2));
return liveRate;
}
catch (TimeoutException)
{
return "$10.00";
}
}
private async Task<string> GetLiveShippingRateAsync()
{
Random rnd = new Random();
int delay = rnd.Next(1000, 4000);
await Task.Delay(delay);
return "$15.50";
}
}