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

IosSwiftSwift2

Ios Problem Overview


I'm updating my code to use Swift, and I'm wondering how to print error details for an exception that matches the 'catch all' clause. I've slightly modified the example from this Swift Language Guide Page to illustrate my point:

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?
}

If I catch an unexpected exception, I need to be able to log something about what caused it.

Ios Solutions


Solution 1 - Ios

I just figured it out. I noticed this line in the Swift Documentation:

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

So, then I tried this:

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

And it gave me a nice description.

Solution 2 - Ios

From The Swift Programming Language:

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

That is, there is an implicit let error in the catch clause:

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

Alternatively, it seems that let constant_name is also a valid pattern, so you could use it to rename the error constant (this might conceivably be handy if the name error is already in use):

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmarkdb314View Question on Stackoverflow
Solution 1 - Iosmarkdb314View Answer on Stackoverflow
Solution 2 - IosArkkuView Answer on Stackoverflow