Start learning free

LESSON 10 OF 173 · BACKEND: HOW THE WEB WORKS

Errors and Timeouts

Practice

Sometimes the problem is not your request but the server. A status in the 500s, like 500 Internal Server Error, means your request was fine but the server failed while answering it: a bug, a database that is down, too much traffic. It isn't your fault, and the same request may work a minute later.

Worse than a 500 is no answer at all. By default HttpClient waits up to 100 seconds for an answer. To set your own limit, pass a cancellation token as the second argument of GetAsync: new CancellationTokenSource(5000).Token cancels the request after 5000 milliseconds, and GetAsync throws a TaskCanceledException. Catch it with try and catch, so your script carries on instead of crashing:

try {
    var response = await http.GetAsync("https://api.example.com/weather", new CancellationTokenSource(5000).Token);
    var data = await response.Content.ReadFromJsonAsync<JsonElement>();
    Console.WriteLine("Weather: " + data.GetProperty("sky"));
} catch (TaskCanceledException) {
    Console.WriteLine("No weather today");
}

The supplier has a route for each problem: /broken always fails, and /slow takes 2 seconds to answer.

GET /broken                    →  500  {"error": "The supplier is down"}
GET /slow  (cancel after 1 s)  →  no answer after 1 second: TaskCanceledException

Your script must print:

/broken: 500
The supplier failed: The supplier is down
/slow: no answer after 1 second

Your task: get /broken and print its status as a number, and for any status of 500 or more, the error from its JSON body. Then get /slow inside a try block, with a token that cancels it after 1000 milliseconds: print its status if it answers in time, and a message in a catch (TaskCanceledException) if it doesn't.


Assignment
Follow the Coding Tutorial to handle a server error and a timeout without crashing.


Hint
(int)response.StatusCode >= 500 catches every server error at once. Inside the try block, the lines after the request run only when an answer came in time.


STEP 1 OF 10
    Ctrl + Enter to check