Catching errors in SwiftUI
Asked Answered
H

1

10

I have a button in some view that calls a function in the ViewModel that can throw errors.

Button(action: {
    do {
        try self.taskViewModel.createInstance(name: self.name)
    } catch DatabaseError.CanNotBeScheduled {
        Alert(title: Text("Can't be scheduled"), message: Text("Try changing the name"), dismissButton: .default(Text("OK")))
    }
}) {
    Text("Save")
}

The try-catch block yields the following error :

Invalid conversion from throwing function of type '() throws -> Void' to non-throwing function type '() -> Void'

This it the createInstance func in the viewModel, the taskModel function handles the error in the same exact way.

func createIntance(name: String) throws {
    do {
        try taskModel.createInstance(name: name)
    } catch {
        throw DatabaseError.CanNotBeScheduled
    }
}   

How to properly catch an error in SwiftUI ?

Harbaugh answered 27/8, 2020 at 17:36 Comment(0)
T
6

Alert is showing using .alert modifier as demoed below

@State private var isError = false
...
Button(action: {
    do {
        try self.taskViewModel.createInstance(name: self.name)
    } catch DatabaseError.CanNotBeScheduled {
        // do something else specific here
        self.isError = true
    } catch {
        self.isError = true
    }
}) {
    Text("Save")
}
 .alert(isPresented: $isError) {
    Alert(title: Text("Can't be scheduled"),
          message: Text("Try changing the name"),
          dismissButton: .default(Text("OK")))
}
Temperament answered 27/8, 2020 at 17:50 Comment(3)
I made the changes but I am still getting the same error. I added the function I am calling to.Harbaugh
Updated... you catch specific error, but also need to add generic catch for all other errors.Temperament
@Harbaugh Did you ever fix the error? I have been working on errors in my application and could not figure this one out. I looked it up and this is the only case of it in Swift I could find.Barris

© 2022 - 2024 — McMap. All rights reserved.