Search code examples
iosswiftuitry-catchthrow

Catching errors in SwiftUI


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 ?


Solution

  • 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")))
    }