Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the error message in Swift 2.0?

I used this method very much in Swift 1.2: NSURLConnection.sendSynchronousRequest(:_:_:_) but this is apparently deprecated in iOS9. It still works however but now it uses the new Swift 2.0 Error Handling and I don't know how I will get the error message if it fails, ex. if time runs out.

I know I have to put it into a do-catch and then say try before the metho but I dont know how to catch the error message.

do {
    let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
    return data 
}
catch _ {
    return nil
}

Before I used NSError and then its description property, but now I have no clue.

like image 282
Arbitur Avatar asked Sep 24 '15 09:09

Arbitur


People also ask

What is error protocol in Swift?

Overview. Any type that declares conformance to the Error protocol can be used to represent an error in Swift's error handling system. Because the Error protocol has no requirements of its own, you can declare conformance on any custom type you create.

How can a function throw an error in Swift?

Sometimes functions fail because they have bad input, or because something went wrong internally. Swift lets us throw errors from functions by marking them as throws before their return type, then using the throw keyword when something goes wrong.

How do Swift developers handle errors?

According to the guides, Swift projects should declare custom error types to signal exceptional conditions (CustomErrorTypes). G-5 shows an example using a struct as an error type; G-1 to G-4 and G-6 recommend using enums as error types.


1 Answers

Use automatic error variable, and you can cast it to NSError if you wish:

catch {
    let nsError = error as NSError
    print(nsError.localizedDescription)
}
like image 122
rshev Avatar answered Sep 21 '22 05:09

rshev