从dataTask completeHandler

时间:2018-07-09 09:57:53

标签: swift nsurlsessiondatatask

如何迅速在这样的完成处理程序中引发错误:

    let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {
        (data, response, error) in
        do {
            //something
            completion(result)
        } catch let jsonError {
            throw CustomError.myerror //THIS DOESN'T WORK
        }
    })
    task.resume()

因为错误是

  

类型'(_,_,_)的throwing函数的无效转换引发->   ()”改为非抛出函数类型“(Data?,URLResponse?,Error?)->   无效

1 个答案:

答案 0 :(得分:7)

短篇小说:throw不能在dataTask完成闭包中

您可以在完成处理程序中返回两个值

...completion: @escaping (ResultType?, Error?)->Void

然后返回

completion(result, nil)
completion(nil, CustomError.myerror)

或更方便地使用具有关联类型的枚举

enum Result {
    case success(ResultType), failure(Error)
}

...completion: @escaping (Result)->Void

然后返回

completion(.success(result))
completion(.failure(CustomError.myerror))

您可以处理结果

foo() { result in
    switch result {
    case .success(let resultType): // do something with the result
    case .failure(let error): // Handle the error
    }
}