
[英]Alamofire 4 Invalid conversion from throwing function of type '(_) throws -> ()' to non-throwing function type '(DataResponse<Any>) -> Void'
[英]try-catch inside closure -> Invalid conversion from throwing to non-throwing function type
我已经用throws标记了我的函数,为什么会迅速迫使我使用do-try-catch块?
我想处理在以下我称之为此函数的地方引发的任何类型的错误。
static func getPosts() throws {
let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1")
let request = URLRequest(url: url!)
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves) as! [String: Any]
}.resume()
}
以下是我遇到的错误的屏幕截图。
您throws
表明您的getPosts()
函数本身将抛出throws
。 但是,它在调用闭包之前完成了,这意味着即使json解析引发异常,您也已经花费了可以捕获和处理异常的时间。
闭合中的错误必须在闭合中处理。 您正在寻找类似的东西
static func getPosts(completion: @escaping (_ error: String) -> Void) {
let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1")
let request = URLRequest(url: url!)
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves) as! [String: Any]
completion("ok")
}catch let error {
print(error)
completion("error")
}
}.resume()
}
从闭包内部捕获错误是不可能的。
合适的解决方案是枚举和完成处理程序
enum PostResult {
case success([String:Any]), failure(Error)
}
func getPosts(completion:@escaping (PostResult)->() ) {
let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1")!
// no URLRequest needed !
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!) as! [String: Any]
completion(.success(json))
} catch {
completion(.failure(error))
}
}.resume()
}
并使用它
getPosts { result in
switch result {
case .success(let json): print(json)
// process json
case .failure(let error): print(error)
// handle error
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.