Search code examples
swiftswiftui

Try await swift errors thrown from here are not handled - Swift 5.5,*


I'm trying to initialize a variable (in a ViewModel) with some value from the db using async await introduced in swift 5.5, but I'm getting the error:

Errors thrown from here are not handled

This is the code:

@Published var userWallets: [Wallet]

init() async {
    // Get current User
    let user = await NetworkController().getUser()
    
    // Publish all wallets
    userWallets = try await getUserWallets(user: user)
}

I have tried to wrap it around a Task but then it says: 'self' captured by a closure before all members were initialized

How to I initialize that value correctly?


Solution

  • In your example, getUserWallets(user:) can throw. You therefore have two choices on how to deal with this:

    1. Make the init throw as well:
    init() async throws {
        // ...
        
        userWallets = try await getUserWallets(user: user)
    }
    

    This means that you have to deal with the error when initializing your struct or class.

    1. Handle the error in some way:
    init() async {
        // ...
        
        do {
            userWallets = try await getUserWallets(user: user)
        } catch {
            // handle the error here in some way
        }
    }