How do I get the error message in Swift 2.0?
Use automatic error
variable, and you can cast it to NSError
if you wish:
catch { let nsError = error as NSError print(nsError.localizedDescription)}
You can now throw any object inheriting ErrorType
, and provide custom handling in the catch
sentence. You can also cast the error to NSError
to access localizedDescription
for handling third party errors.
Casting an enum ErrorType
will produce a NSError
with domain
equal to the enum name, code
equal to the enum value and an auto-generated localizedDescription
with the following format:
The operation couldn’t be completed. (DOMAIN error CODE.)
For example, the following code:
enum AwfulError: ErrorType { case Bad case Worse case Terrible}func throwingFunction() throws { throw AwfulError.Worse}do { try throwingFunction()}catch AwfulError.Bad { print("Bad error")}catch let error as NSError { print(error.localizedDescription)}
Will print
The operation couldn’t be completed. (AwfulError error 1.)
Despite the question title specifying Swift 2, this answer is for Swift 3.
As @redent84 points out, since Swift 2 an Error object may be a home-made one. Here's a method I wrote to analyze and print the default error object available in a "catch" statement that doesn't specify any specific error type:
// Method to print an unknown Error type object to the system output. static func printCaughtError(_ unknownError : Error) { let objectDescription = String(describing: unknownError) let localizedDescription = unknownError.localizedDescription if localizedDescription != "" { if localizedDescription.contains(objectDescription) { print(localizedDescription) return } if !objectDescription.contains(localizedDescription) { print(objectDescription + ": " + localizedDescription) return } } print(objectDescription) }
Then you can call it like this:
catch { printCaughtError(error) }