11

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?

0

3 Answers 3

11

For some reason Task is designed to silently fail when any errors are thrown inside the closure. Tasks do have a result property that you can read when the task has completed, but according to the documentation it will block the current thread where it's executed.

My preferred solution is to create a convenience initializer for Task that takes a failure closure.

This is what my custom initializer looks 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)
}
4
  • 3
    Yeah, it just seems apple should have provided a 2nd trailing closure by default for this, instead of this weird behavior.
    – user187676
    Commented Dec 11, 2021 at 10:41
  • Brilliant, and simple! I've added my own answer based on your solution here, the primary difference being I changed it from an initializer to a static do method, but the internals are identical. Check it out here: stackoverflow.com/a/76349401/168179 Commented May 28, 2023 at 0:08
  • Also, a suggestion for your own code, consider adding @discardableResult to your initializer to stop compiler warnings when you aren't storing the resulting Task. 🙂 Commented May 28, 2023 at 0:09
  • If you wrap do/catch then you can’t take advantage of catch let and catch as syntax as a well as multiple catches.
    – malhal
    Commented Oct 18, 2023 at 8:44
1

Task.do/catch

Below is an extension method on Task that allows simple and familiar do/catch syntax for handling errors in async operations.

The design is based on Emilio Pelaez's answer here on the same page where he used a custom initializer with a trailing catch handler. I've instead implemented it as a static method called do, also with a trailing catch handler, to be more similar with the familiar do/catch syntax Swift developers are used to. The intent is to add clarity at the call site, a core tenet of Swift's API design guidelines.

That said, the majority of the credit goes to his answer for the overall concept so if you like this, please vote him up as well.

extension Task
where Success == Void,
      Failure == Never {

    typealias ThrowingOperation = () async throws -> Void
    typealias ErrorHandler = (Error) async -> Void

    /// Creates a throwing task with familiar do-catch-like syntax
    @discardableResult
    static func `do`(
        priority: TaskPriority? = nil,
        throwingOperation: @escaping ThrowingOperation,
        `catch` errorHandler: @escaping ErrorHandler
    ) -> Self {
        
        return Task(priority: priority) {
            do { try await throwingOperation() }
            catch { await errorHandler(error) }
        }
    }
}

With the above in place, here's how you use it:

func tryToSleep() {

    // Start's an async 'do' operation
    Task.do { // You're now in a task so you can 'await' as needed
        print("My task is going to sleep asynchronously...")
        try await Task.sleep(for: .seconds(4))
        print("Grrr! I woke up!")
        throw SleepError.notAMorningPerson
    }
    catch: { error in // All unhandled errors thrown in the task are passed here
        print("The task threw an error: \(error)")
    }
}
0

While it has not been officially proposed (reader: please do that if you're so inclined!), there has been talk on the Swift forums that only allowing for Task<Void, Never> to be "@discardableResult" would be a good enough solution to the problem.

As it is now, Task.init and Task.detached are always discardable. If they were not, the thinking goes, the "Result … is unused" message would cause the programmer to be aware that further action is warranted…

…e.g. by explicitly disregarding a result when the task's Success is not Void

_ = Task { "🔮" }

…or by being nudged to store the task, and deal with the error later.

let task = // Task<Void, Error>
  Task.detached {
    try await myThrowingFunction()
    runWhenSuccessful()
  }

await task.value // Property access can throw but is not marked with 'try'

I support this proposed change. But it would still be possible, as it is now, to disregard a task that completed with an error, using an underscore, and I don't think that underscore represents intent very well:

_ = Task.detached {
  try await myThrowingFunction()
  runWhenSuccessful()
}

The only way to enforce handling of the error is to get the idea that the operation closure does not throw, into the type system, using an explicit Never.

invalid conversion from throwing function of type '@Sendable () async throws -> ()' to non-throwing function type '@Sendable () async -> ()'

Task<_, Never>.detached {
  try await myThrowingFunction()
  runWhenSuccessful()
}

do/catch:

Task<_, Never>.detached {
  do {
    try await myThrowingFunction()
    runWhenSuccessful()
  } catch { }
}

Explicit Error perhaps carries a better idea of intention than _ = Task:

Task<_, Error>.detached {
  try await myThrowingFunction()
  runWhenSuccessful()
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.