0Pricing
Swift Academy · Lesson

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 Error

Checking 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

  1. URLSession data(from:) with async/await
  2. Codable: Encoding and Decoding JSON
  3. Error Handling and HTTP Status Codes
  4. Retry Logic and Background URLSession
← Back to Swift Academy