如何在 Swift 中打印 'catch all' 异常的详细信息?

How to print details of a 'catch all' exception in Swift?

我正在更新我的代码以使用 Swift,我想知道如何打印与 'catch all' 子句匹配的异常的错误详细信息。我稍微修改了此 Swift Language Guide Page 中的示例以说明我的观点:

do {
    try vend(itemNamed: "Candy Bar")
    // Enjoy delicious snack
} catch VendingMachineError.InvalidSelection {
    print("Invalid Selection.")
} catch VendingMachineError.OutOfStock {
    print("Out of Stock.")
} catch VendingMachineError.InsufficientFunds(let amountRequired) {
    print("Insufficient funds. Please insert an additional $\(amountRequired).")
} catch {
    // HOW DO I PRINT OUT INFORMATION ABOUT THE ERROR HERE?
}

如果我捕获到意外异常,我需要能够记录导致异常的原因。

我刚刚弄明白了。我在 Swift 文档中注意到这一行:

If a catch clause does not specify a pattern, the clause will match and bind any error to a local constant named error

所以,然后我尝试了这个:

do {
    try vend(itemNamed: "Candy Bar")
...
} catch {
    print("Error info: \(error)")
}

它给了我一个很好的描述。

来自Swift编程语言:

If a catch clause does not specify a pattern, the clause will match and bind any error to a local constant named error.

catch子句中隐含了let error

do {
    // …
} catch {
    print("caught: \(error)")
}

或者,let constant_name 似乎也是一个有效的模式,因此您可以使用它来重命名错误常量(如果名称 error 已被使用,这可能会很方便) :

do {
    // …
} catch let myError {
   print("caught: \(myError)")
}