如何迅速在这样的完成处理程序中引发错误:
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?)-> 无效
答案 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
}
}