ios - Bolt-Swift : error handling

标签 ios swift bolt

我想使用 BoltsSwift ( https://github.com/BoltsFramework/Bolts-Swift )。

但我无法正确处理错误。

在下面的示例中,为什么运行的是“taskHello2.continueOnSuccessWith”而不是“taskHello2.continueOnErrorWith”?

谢谢

func testTask() {
    let taskHello1 = echo("hello1")
    let taskHello2 = taskHello1.continueOnSuccessWith(continuation: { (task) -> Task<String> in
        let taskResult = self.echo("error")
        return taskResult
    })
   _ = taskHello2.continueOnErrorWith(continuation: { (task) -> Task<String> in
        let taskResult = self.echo("Error received")
        return taskResult
    })
    _ = taskHello2.continueOnSuccessWith(continuation: { (task) -> Task<String> in
        let taskResult = self.echo("Success received")
        return taskResult
    })
}

func echo(_ text: String) -> Task<String> {
    let taskCompletionSource = TaskCompletionSource<String>()
    print("=> \(text)")
    switch (text) {
    case "error":
        let error = NSError(domain: "domain", code: -1, userInfo: ["userInfo": "userInfo"])
        taskCompletionSource.set(error: error)
    case "cancel":
        taskCompletionSource.cancel()
    default:
        taskCompletionSource.set(result: text)
    }
    return taskCompletionSource.task
}

输出:

=> hello1
=> error
=> Success received

最佳答案

函数continueOnErrorWith(continuation:)仅在出现错误时运行——任务发生故障。

在您的 testTask() 函数中,taskHello1 被执行(或成功),因此 'hello1' 被打印到控制台。

在代码中:

let taskHello2 = taskHello1.continueOnSuccessWith(continuation: { (task) -> Task<String> in
        let taskResult = self.echo("error")
        return taskResult
    })

由于 taskHello1 已经成功,因此闭包内的代码被执行并且'错误'打印。

内部代码:

_ = taskHello2.continueOnErrorWith(continuation: { (task) -> Task<String> in
    let taskResult = self.echo("Error received")
    return taskResult
})

由于taskHello2未遇到错误,闭包内的代码未执行并且“收到错误” 未打印到控制台。

代码中类似:

_ = taskHello2.continueOnSuccessWith(continuation: { (task) -> Task<String> in
        let taskResult = self.echo("Success received")
        return taskResult
    })

由于taskHello2成功,闭包内的代码被执行并且'成功收到'打印。

关于ios - Bolt-Swift : error handling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52046135/

相关文章:

iphone - PFQuery 排除特定列

ios - 核心蓝牙外设每 30 秒断开一次

arrays - 从数组中删除自定义类的元素

slack - 松弛 expired_trigger_id 错误的原因可能是什么?

java - apache Storm - 在单节点中正确运行 jar,但在多节点中不能正确运行

iphone - 从 nib 文件加载 View

ios - 我可以设置 transient 属性来获取吗?

swift - 在 SwiftUI 中将数据从一个 ViewModel 传递到另一个 ViewModel?

ios - 如何在 Swift 3、4 和 5 中编写 dispatch_after GCD?

neo4j - 使用Kubernetes Ingress公开Neo4j Bolt