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.
Request
↓
Possible Errors at Multiple Stages
↓
Handle Each Error Appropriately
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
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