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 ?
Handling Errors Using Do-Catch. You use a do - catch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it's matched against the catch clauses to determine which one of them can handle the error.
There are four ways to handle errors in Swift: — You can propagate the error from a function to the code that calls that function. — Handle the error using a do - catch statement. — Handle the error as an optional value (try?).
You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed. Finally block may not get executed in certain exceptions.
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")))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With