Ios 尝试在封口内捕捉->;从抛出函数类型到非抛出函数类型的转换无效
我已经用投掷标记了我的功能,为什么swift强迫我使用do-try-catch挡块 我想处理在下面调用此函数时抛出的任何类型的错误Ios 尝试在封口内捕捉->;从抛出函数类型到非抛出函数类型的转换无效,ios,swift,error-handling,try-catch,Ios,Swift,Error Handling,Try Catch,我已经用投掷标记了我的功能,为什么swift强迫我使用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
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()
}
下面是我收到的错误屏幕截图。您的
抛出
表示您的getPosts()
函数本身将抛出。但是,它在调用闭包之前完成,这意味着即使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
}
}
没有屏幕截图,请参见。