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 ?

pawello2222
  • 46,897
  • 22
  • 145
  • 209
ChesterK2
  • 320
  • 3
  • 11

1 Answers1

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")))
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 1
    I made the changes but I am still getting the same error. I added the function I am calling to. – ChesterK2 Aug 27 '20 at 17:53
  • 1
    Updated... you catch specific error, but also need to add generic catch for all other errors. – Asperi Aug 27 '20 at 17:58
  • @ChesterK2 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. – DischordDynne Mar 13 '23 at 21:57