如何从 do 块中使用 throw?
How to use throw from within do block?
如果可能的话,我想从 do 块中抛出错误
我有一个函数 getWeatherBy,它被标记为一个投掷函数。我在应用程序其他地方的代码取决于此抛出。我在这个函数内部有一个 JSONDecoder.decode ,它本身就是抛出函数,我在 do 块中有它。但是,如果 JSONDecoder 出现错误,我想从 getWeatherBy 中抛出错误,但由于该抛出是在 JSONDecoder 内部发生的,因此会在那里被捕获。
抱歉代码乱七八糟。我还是个新手,欢迎任何改进此代码的想法!
func getWeatherBy(city: String, completion: ((WeatherRecord) -> ())?) throws {
let trimmedCityName = (city as NSString).replacingOccurrences(of: " ", with: "+")
let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(trimmedCityName.lowercased())&appid=\(self.OpenWeatherAPIkey)&units=metric")
guard url != nil else { return }
print(url!)
let networkTask: URLSessionDataTask = URLSession.shared.dataTask(with: url!) {
(data, response, error) in
guard let data = data else { return }
do {
let decoded = try JSONDecoder().decode(WeatherData.self, from: data)
if (decoded.main != nil) {
if (decoded.coord?.lat != nil) {
DispatchQueue.main.async {
let record = WeatherRecord(temperature: Float(decoded.main!.temp), date: Date(), coordinates: CLLocationCoordinate2D(latitude: decoded.coord!.lat, longitude: decoded.coord!.lon), distance: 0.0)
if completion != nil {
completion!(record)
}
}
}
} else {
throw serviceError.cityNotFound
}
if (decoded.message != nil) {
print("Message: \(decoded.message!)")
DispatchQueue.main.async {
if (String(describing: decoded.message!).contains("Your account is temporary blocked") == true) {
}
if (decoded.message! != "Nothing to geocode") || String(describing: decoded.message!).contains("Your account is temporary blocked") != false {
}
}
}
} catch DecodingError.keyNotFound(let key, let context) {
Swift.print("Could not find key \(key) in JSON: \(context.debugDescription)")
} catch DecodingError.valueNotFound(let type, let context) {
Swift.print("Could not find type \(type) in JSON: \(context.debugDescription)")
} catch DecodingError.typeMismatch(let type, let context) {
Swift.print("Type mismatch for type \(type) in JSON: \(context.debugDescription) \(context)")
} catch DecodingError.dataCorrupted(let context) {
Swift.print("Data found to be corrupted in JSON: \(context.debugDescription)")
} catch let error as NSError {
NSLog("Error in read(from:ofType:) domain= \(error.domain), description= \(error.localizedDescription)")
}
}
最常见的方式是添加错误with/without newResult
func getWeatherBy(city: String, completion: ((WeatherRecord? , Error?) -> ()))
你不能立即从异步方法中抛出异常
如果可能的话,我想从 do 块中抛出错误
我有一个函数 getWeatherBy,它被标记为一个投掷函数。我在应用程序其他地方的代码取决于此抛出。我在这个函数内部有一个 JSONDecoder.decode ,它本身就是抛出函数,我在 do 块中有它。但是,如果 JSONDecoder 出现错误,我想从 getWeatherBy 中抛出错误,但由于该抛出是在 JSONDecoder 内部发生的,因此会在那里被捕获。
抱歉代码乱七八糟。我还是个新手,欢迎任何改进此代码的想法!
func getWeatherBy(city: String, completion: ((WeatherRecord) -> ())?) throws {
let trimmedCityName = (city as NSString).replacingOccurrences(of: " ", with: "+")
let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(trimmedCityName.lowercased())&appid=\(self.OpenWeatherAPIkey)&units=metric")
guard url != nil else { return }
print(url!)
let networkTask: URLSessionDataTask = URLSession.shared.dataTask(with: url!) {
(data, response, error) in
guard let data = data else { return }
do {
let decoded = try JSONDecoder().decode(WeatherData.self, from: data)
if (decoded.main != nil) {
if (decoded.coord?.lat != nil) {
DispatchQueue.main.async {
let record = WeatherRecord(temperature: Float(decoded.main!.temp), date: Date(), coordinates: CLLocationCoordinate2D(latitude: decoded.coord!.lat, longitude: decoded.coord!.lon), distance: 0.0)
if completion != nil {
completion!(record)
}
}
}
} else {
throw serviceError.cityNotFound
}
if (decoded.message != nil) {
print("Message: \(decoded.message!)")
DispatchQueue.main.async {
if (String(describing: decoded.message!).contains("Your account is temporary blocked") == true) {
}
if (decoded.message! != "Nothing to geocode") || String(describing: decoded.message!).contains("Your account is temporary blocked") != false {
}
}
}
} catch DecodingError.keyNotFound(let key, let context) {
Swift.print("Could not find key \(key) in JSON: \(context.debugDescription)")
} catch DecodingError.valueNotFound(let type, let context) {
Swift.print("Could not find type \(type) in JSON: \(context.debugDescription)")
} catch DecodingError.typeMismatch(let type, let context) {
Swift.print("Type mismatch for type \(type) in JSON: \(context.debugDescription) \(context)")
} catch DecodingError.dataCorrupted(let context) {
Swift.print("Data found to be corrupted in JSON: \(context.debugDescription)")
} catch let error as NSError {
NSLog("Error in read(from:ofType:) domain= \(error.domain), description= \(error.localizedDescription)")
}
}
最常见的方式是添加错误with/without newResult
func getWeatherBy(city: String, completion: ((WeatherRecord? , Error?) -> ()))
你不能立即从异步方法中抛出异常