enum NetworkError: Error {
case badURL
case requestFailed
case serverError(statusCode: Int)
}
func fetchData(from urlString: String) throws -> Data {
guard let url = URL(string: urlString) else {
throw NetworkError.badURL
}
let (data, response, error) = URLSession.shared.syncRequest(with: url)
if let error = error {
throw Network
Error.requestFailed
}
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
throw NetworkError.serverError(statusCode: httpResponse.statusCode)
}
return data!
}
do {
let data = try fetchData(from: "https://api.example.com/data")
print("Data received: \(data)")
} catch NetworkError.badURL {
print("Invalid URL")
} catch NetworkError.requestFailed {
print("Request failed")
} catch NetworkError.serverError(let statusCode) {
print("Server error with status code: \(statusCode)")
} catch {
print("Unknown error: \(error)")
}