Exercise: Shipping API Timeout Fallback
Problem statement
Your e-commerce checkout page fetches live shipping rates from a third-party logistics API. Sometimes, this API is extremely slow or unresponsive. To ensure the customer isn't stuck waiting forever, you must enforce a strict 2-second timeout on the request. If the API fails to respond in time, your utility must catch the timeout and return a standard flat shipping rate of $10.00 instead.
Task requirements
Call the simulated
GetLiveShippingRateAsyncmethod from withinGetRateWithFallbackAsync.Apply a 2-second timeout to the task.
If successful within the time limit, return the live rate.
If it times out, catch the error and return the fallback rate of $10.00.
Constraints
You must use the
.WaitAsync(TimeSpan)method to enforce the timeout constraint.You must wrap the await call in a
try-catchblock inside the utility class.You must strictly catch
TimeoutException, not the genericExceptionbase class.
Good luck trying the exercise! If you’re unsure how to proceed, check the “Solution” tab above.
Get hints
Chain
.WaitAsync(TimeSpan.FromSeconds(2))directly to theGetLiveShippingRateAsync()call inside thetryblock.Return the result of the
awaitimmediately if it succeeds.In the
catch (TimeoutException)block, return the string"$10.00".
Exercise: Shipping API Timeout Fallback
Problem statement
Your e-commerce checkout page fetches live shipping rates from a third-party logistics API. Sometimes, this API is extremely slow or unresponsive. To ensure the customer isn't stuck waiting forever, you must enforce a strict 2-second timeout on the request. If the API fails to respond in time, your utility must catch the timeout and return a standard flat shipping rate of $10.00 instead.
Task requirements
Call the simulated
GetLiveShippingRateAsyncmethod from withinGetRateWithFallbackAsync.Apply a 2-second timeout to the task.
If successful within the time limit, return the live rate.
If it times out, catch the error and return the fallback rate of $10.00.
Constraints
You must use the
.WaitAsync(TimeSpan)method to enforce the timeout constraint.You must wrap the await call in a
try-catchblock inside the utility class.You must strictly catch
TimeoutException, not the genericExceptionbase class.
Good luck trying the exercise! If you’re unsure how to proceed, check the “Solution” tab above.
Get hints
Chain
.WaitAsync(TimeSpan.FromSeconds(2))directly to theGetLiveShippingRateAsync()call inside thetryblock.Return the result of the
awaitimmediately if it succeeds.In the
catch (TimeoutException)block, return the string"$10.00".