捕捉 SwiftUI 中的错误

10

我在某个视图中有一个按钮,该按钮调用ViewModel中的函数,该函数可能会抛出错误。

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

try-catch 块会产生以下错误:
Invalid conversion from throwing function of type '() throws -> Void' to non-throwing function type '() -> Void'

这是viewModel中的createInstance功能,taskModel函数以完全相同的方式处理错误。
func createIntance(name: String) throws {
    do {
        try taskModel.createInstance(name: name)
    } catch {
        throw DatabaseError.CanNotBeScheduled
    }
}   

如何在SwiftUI中正确捕获错误?

1个回答

6

使用.alert修饰符展示警报,如下所示。

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

1
我已经做了更改,但仍然遇到相同的错误。我已经添加了我正在调用的函数。 - ChesterK2
1
更新...您已经捕捉到了特定的错误,但还需要添加一个通用的捕捉以处理其他所有错误。 - Asperi
@ChesterK2 你有修复这个错误吗?我一直在处理我的应用程序中的错误,但无法解决这个问题。我查了一下,这是我在 Swift 中能找到的唯一一个这种情况。 - DischordDynne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接