Spot the bug
When the server returns 404, users see a confusing decoding error. Tap the line to fix.
func loadUser(id: Int) async throws -> User {let url = URL(string: "https://api.example.com/users/\(id)")!let (data, _) = try await URLSession.shared.data(from: url)return try JSONDecoder().decode(User.self, from: data)}
Hint 1 of 1
Does URLSession throw for HTTP errors?
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 3
let (data, _) = try await URLSession.shared.data(from: url)
Line 3 throws away the response, so a 404 body is decoded as a User. Keep the response, check (response as? HTTPURLResponse)?.statusCode is 200...299, and throw a clear error otherwise.