Concept

Error handling in networking ensures that failures are properly detected and handled at different stages of a request.

It prevents crashes and allows the application to respond correctly to failures.


Key Idea

Request
↓
Possible Errors at Multiple Stages
↓
Handle Each Error Appropriately

Types of Errors

1. Network Errors

Occurs when the request fails to reach the server.

if let error = error {
    print("Network Error:", error.localizedDescription)
}

Examples:

no internet connection
timeout
DNS failure

2. HTTP Errors

Occurs when the server responds with an error status code.

if !(200...299).contains(httpResponse.statusCode) {
    print("HTTP Error:", httpResponse.statusCode)
}

Examples:

400 → Bad Request
401 → Unauthorized
404 → Not Found
500 → Server Error