Start learning free

LESSON 10 OF 173 · BACKEND: HOW THE WEB WORKS

Errors and Timeouts in Go

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. http.Get waits as long as the server takes. An http.Client with a Timeout gives up when the time runs out: its Get then returns an error and a nil response. Check err before you touch the response, so your program carries on instead of crashing:

client := http.Client{Timeout: 5 * time.Second}
response, err := client.Get("https://api.example.com/weather")
if err != nil {
    fmt.Println("No weather today")
    return
}
defer response.Body.Close()
fmt.Println("Weather:", response.StatusCode)

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  (Timeout 1 s)  →  no answer after 1 second: an error

Your program 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, and for any status of 500 or more, the error from its JSON body. Then get /slow with a client whose Timeout is time.Second: if it gives an error, print a message and return; if it answers in time, print its status.


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


Hint
response.StatusCode >= 500 catches every server error at once. After a timeout, response is nil: print the message and return before any line reads it.


STEP 1 OF 12
    Ctrl + Enter to check

    Web Server Errors in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free