Home > Enterprise >  Throwing erros inside a root Task
Throwing erros inside a root Task

Time:12-12

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.

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

CodePudding user response:

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)
}
  • Related