HTTP Error Handling
Start with HTTP Error Handling
In this lesson, explore http error handling through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of http error handling.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Differentiate bad client requests from server failures. Send a clear status code and safe explanation; log internal details separately rather than leaking them in API responses.
Return promptly after writing an error. Otherwise a handler may accidentally append a success response to the error body.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func handler(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("id") == "" {
http.Error(w, "missing id", http.StatusBadRequest)
return
}
fmt.Fprint(w, "found")
}
func main() {
rec := httptest.NewRecorder()
http.HandlerFunc(handler).ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
fmt.Println("Status:", rec.Code)
}
Output
Status: 400Trace what the program does
Because the URL omits id, the handler writes a 400 response and returns before printing found.
Avoid common mistakes
- Never expose database credentials or stack traces in client-facing error text.
- Check errors returned by downstream I/O before reporting success.
Try it yourself
Add a not-found branch that sends status 404 for an unknown task ID.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced HTTP Error Handling in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.