我想在完成处理程序中捕获错误,以便调用者可以捕获它们。我有以下代码:
func application(application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool
showActivityIndicator()
}
它返回json,但是可能会抛出错误吗?例如,当数据== nil时,抛出错误并在调用者端捕获它?
来电方:
private func data_request(url : String, params : String, regularRequest : Bool, completionHandler: @escaping (_ json: Any) -> ()){
let buildUrl = BuildUrl().createUrl(url: url, regularRequest: regularRequest);
if(buildUrl.1){
print("There is something wrong with creating the url");
}
let url:NSURL = NSURL(string: buildUrl.0)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let paramString = (params != "") ? params : ""
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest) {
(data, response, error) in
if data == nil {
print("dataTaskWithRequest error: \(error)")
return
} else {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
completionHandler(json)
} catch {
if let data = data,
let html = String(data: data, encoding: String.Encoding.utf8) {
print(html)
}
print("error serializing JSON: \(error)")
}
}
}
task.resume()
}
实际来电者:
func insertData(roomName : String, completionHandler: @escaping (_ error : Bool, _ message : String) -> ()) {
do {
let params = "name=/(roomName)";
data_request(url: createAndJoinRoom, params: params,regularRequest: true) { json in
completionHandler(error, message)
};
} catch {
}
}
我想在我的"实际来电者#34;并在那里处理错误。我认为我修改了insertData方法中的所有错误,因此我可以捕获一个包含不同错误消息的错误。
我该如何实现?
答案 0 :(得分:2)
您不能将throw
与完成处理程序结合使用。
另一种方法是使用带有关联类型的枚举
enum Result {
case success, failure(Error)
}
或者更通用,能够传递不同但不同的返回类型
enum Result<T> {
case success(T), failure(Error)
}
然后您可以在完成处理程序中传递单个类型
... completionHandler: @escaping (Result) -> ()) { ...
并处理返回的值
... { result in
switch result {
case .success : print("success")
case .failure(let error) : print(error)
}
}
这是一种非常方便有效的方式