集成Tomorrow.io API时的错误处理问题:未捕获抛出错误
解决Tomorrow.io API集成中的错误处理问题
你遇到的错误核心原因是:async函数内使用try但未处理抛出的错误,Swift要求所有抛出的错误必须被捕获,或是让函数本身向外传递错误。下面提供两种可行的解决方式:
方式一:用do-catch捕获并处理错误
把try await的请求代码包裹在do块中,通过catch捕获网络请求、URL解析等环节可能出现的错误:
import Foundation func WeatherAPI() async { guard let url = URL(string: "https://api.tomorrow.io/v4/weather/forecast") else { print("无效的基础URL") return } guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { print("无法解析URL组件") return } let queryItems: [URLQueryItem] = [ URLQueryItem(name: "location", value: "Location..."), URLQueryItem(name: "apikey", value: "API Code Not Going to be shown"), ] components.queryItems = (components.queryItems ?? []) + queryItems guard let finalURL = components.url else { print("无法生成最终请求URL") return } var request = URLRequest(url: finalURL) request.httpMethod = "GET" request.timeoutInterval = 10 request.allHTTPHeaderFields = [ "accept": "application/json", "accept-encoding": "deflate, gzip, br" ] do { let (data, _) = try await URLSession.shared.data(for: request) print(String(decoding: data, as: UTF8.self)) } catch { print("请求失败:\(error.localizedDescription)") // 这里还可以根据错误类型做针对性处理,比如判断是否是网络超时、无网络连接等 } }
方式二:让函数向外抛出错误
如果希望由调用该函数的地方处理错误,可以将函数声明为throws async,把错误传递给调用者:
import Foundation func WeatherAPI() async throws { guard let url = URL(string: "https://api.tomorrow.io/v4/weather/forecast") else { throw NSError(domain: "WeatherAPI", code: 1, userInfo: [NSLocalizedDescriptionKey: "无效的基础URL"]) } guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { throw NSError(domain: "WeatherAPI", code: 2, userInfo: [NSLocalizedDescriptionKey: "无法解析URL组件"]) } let queryItems: [URLQueryItem] = [ URLQueryItem(name: "location", value: "Location..."), URLQueryItem(name: "apikey", value: "API Code Not Going to be shown"), ] components.queryItems = (components.queryItems ?? []) + queryItems guard let finalURL = components.url else { throw NSError(domain: "WeatherAPI", code: 3, userInfo: [NSLocalizedDescriptionKey: "无法生成最终请求URL"]) } var request = URLRequest(url: finalURL) request.httpMethod = "GET" request.timeoutInterval = 10 request.allHTTPHeaderFields = [ "accept": "application/json", "accept-encoding": "deflate, gzip, br" ] let (data, _) = try await URLSession.shared.data(for: request) print(String(decoding: data, as: UTF8.self)) } // 调用示例: // do { // try await WeatherAPI() // } catch { // print("处理错误:\(error)") // }
额外提醒:原代码中的!强制解包风险很高,一旦URL或组件解析失败会直接导致崩溃,上面的代码用guard let替换了强制解包,提升了代码的稳定性。
内容的提问来源于stack exchange,提问作者Train Lover
相关产品推荐
相关产品推荐

