在 SwiftUI 中捕获错误
Catching errors in 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")))
}
我在某些视图中有一个按钮调用 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")))
}