try-catch内封闭 - >从投掷到非投掷函数类型的转换无效

时间:2017-06-30 07:04:01

标签: ios swift error-handling try-catch

我已经用throws标记了我的函数,为什么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
    session.dataTask(with: request) { (data, response, error) in

        let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves) as! [String: Any]  

    }.resume()        
}

下面是我得到的错误的屏幕截图。

2 个答案:

答案 0 :(得分:0)

您的throws表示您的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()        
}

答案 1 :(得分:0)

从闭包中捕捉错误是不可能的。

合适的解决方案是枚举和完成处理程序

h() // rvalue (prvalue)
g() // glvalue and rvalue (xvalue)
f() // glvalue (lvalue)
i   // glvalue (lvalue)
*p  // glvalue (lvalue)

std::move(i)  // glvalue and rvalue(xvalue)

并使用它

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()
}