Fred
Fred

Reputation: 13

Bolt-Swift: error handling

I want to use BoltsSwift (https://github.com/BoltsFramework/Bolts-Swift).

But I am not able to handle errors correctly.

In the below sample, why the "taskHello2.continueOnSuccessWith" is running instead of "taskHello2.continueOnErrorWith" ?

Thank you

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
}

output:

=> hello1
=> error
=> Success received

Upvotes: 0

Views: 360

Answers (1)

naeemjawaid
naeemjawaid

Reputation: 514

The function continueOnErrorWith(continuation:) only runs when there is an error—the task is faulted.

In your testTask() function, taskHello1 is executed—or succeeded—and hence 'hello1' is printed to console.

In code:

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

since taskHello1 had already met success, the code inside the closure is executed and 'error' is printed.

Inside code:

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

since taskHello2 had not met error, the code inside the closure is not executed and 'Error received' is not printed to console.

Similarly in code:

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

since taskHello2 had met success, the code inside the closure is executed and 'Success received' is printed.

Upvotes: 0

Related Questions