微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

捕捉SwiftUI中的错误

如何解决捕捉SwiftUI中的错误

在某些视图中有一个按钮,该按钮在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中正确捕获错误

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。