swift - 如何在捕获中打印错误

标签 swift error-handling enums try-catch

catch let error as LocksmithError{
print(error)// it would print the case of the error.
}

但是如果我这样做

catch LocksmithError.Duplicate{

}

catch{
print (LocksmithError) // Obviously I would just print LocksmithError, it won't print the case
print (LocksmithError.rawValue) // prints nothing
}

我的问题是:使用第二种方法是否有任何我可以实际检索的方法以及错误的值/大小写?或者,如果我没有在入口点(即捕获点)获得正确的值(value),那么我就会错过这样做的机会!

最佳答案

catch block 是排他性的,按顺序求值。当匹配成功时,我们停止

那么,让我们考虑一下这个结构:

catch LocksmithError.Duplicate {
    // 1
    print("duplicate")
}
catch {
    // 2
    print(error)
}

如果我们在 1,则范围内的是 LocksmithError.Duplicate

如果我们在 2,那么在范围内的是每一种被捕获的其他错误。您无法在此处获取 LocksmithError.Duplicate,因为ex hypothesi 它会在 1 中被捕获,而我们不会这里。

现在,会这样做:

catch let err as LocksmithError {
    // 1
    print(err)
}
catch {
    // 2
    print(error)
}

这可能就是您所追求的;它为我们提供了一个值 err,它将错误带入 1 中的花括号中。 (自动 error 值仅存在于最终的 catch-all catch block 中。)

关于swift - 如何在捕获中打印错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40183711/

相关文章:

ios - 如何将文本字段数据从一个 View Controller 发送到多个 View Controller

shell - 使用 shell 输出对 condor 进行错误处理

objective-c - 这两个枚举有什么区别

python - python 中的枚举有什么好的用例?

快速收缩动画

Swift 3 UICollectionView 错误

ios - Swift Admob 控制台显示模拟器设备 ID 但在 iPhone 上运行时不显示?

javascript - AngularJS,IONIC [$compile :ctreq]

php - 用户友好的 PHP 错误消息

swift - 什么决定了协议(protocol)一致性的优先级?