Error Handling and HTTP Status Codes
Checking response status codes and mapping errors into typed domain errors.
HTTP Status Ranges
HTTP responses signal success or failure via status codes: 2xx success, 3xx redirect, 4xx client error, 5xx server error.
// 200 OK, 201 Created
// 400 Bad Request, 401 Unauthorized, 404 Not Found
// 500 Internal Server ErrorChecking Status in Swift
Cast URLResponse to HTTPURLResponse and check statusCode after an async request.
let (data, response) = try await URLSession.shared.data(from: url)
guard let http = response as? HTTPURLResponse else {
throw NetworkError.invalidResponse
}
guard (200..<300).contains(http.statusCode) else {
throw NetworkError.httpError(http.statusCode)
}All lessons in this course
- URLSession data(from:) with async/await
- Codable: Encoding and Decoding JSON
- Error Handling and HTTP Status Codes
- Retry Logic and Background URLSession