Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Throwing erros inside a root Task

I can’t find anything in the docs how the following behavior is defined

// task-less context
Task.detached {
    try await myThrowingFunction()
    runWhenSuccessful()
}

The method returns on the throwing line and discards the error and runWhenSuccessful() will never be called. While it makes sense in some way, I at least expected it to trigger an assertion failure or something for the unhandled error.

What is the correct way to deal with this, since I can’t handle errors in any parent task.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Am I expected to wrap everything in the closure in a do/catch every time?

>Solution :

It looks to me that by design the Task expects you to deal with the error inside the block by using do/catch, and if you don’t the error is discarded.

Tasks do have a result property that you can read when the task has completed, but it will block the current thread, so it’s probably not what you want.

If you use this pattern often, you could create a convenience initializer for Task that takes a failure closure.

This is what the custom initializer would look like, and how it would be used:

extension Task where Failure == Never, Success == Void {
    init(priority: TaskPriority? = nil, operation: @escaping () async throws -> Void, `catch`: @escaping (Error) -> Void) {
        self.init(priority: priority) {
            do {
                _ = try await operation()
            } catch {
                `catch`(error)
            }
        }
    }
}

Task {
    try await asyncTask()
} catch: { error in
    handle(error)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading