Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching errors in SwiftUI

Tags:

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 ?

like image 227
ChesterK2 Avatar asked Aug 27 '20 17:08

ChesterK2


People also ask

Do-catch in IOS Swift?

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.

What is error handling in Swift?

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?).

How do you handle errors in catch block?

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.


1 Answers

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")))
}
like image 115
Asperi Avatar answered Oct 02 '22 07:10

Asperi