【问题标题】:Catching errors in SwiftUI在 SwiftUI 中捕获错误
【发布时间】:2020-08-27 17:36:43
【问题描述】:

我在某些视图中有一个按钮,它调用 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 中的错误?

【问题讨论】:

    标签: ios swiftui try-catch throw


    【解决方案1】:

    使用.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")))
    }
    

    【讨论】:

    • 我进行了更改,但仍然遇到相同的错误。我添加了我要调用的函数。
    • 已更新...您捕获特定错误,但还需要为所有其他错误添加通用捕获。
    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多