How do I get the error message in Swift 2.0?

2019-02-11 15:07发布

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.

3条回答
贼婆χ
2楼-- · 2019-02-11 15:19

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.)

查看更多
成全新的幸福
3楼-- · 2019-02-11 15:35

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

catch {
    let nsError = error as NSError
    print(nsError.localizedDescription)
}
查看更多
迷人小祖宗
4楼-- · 2019-02-11 15:40

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)
    }
查看更多
登录 后发表回答