0

I am using the code below.

func getData(url: String) {
    if let url = NSURL(string: url) {
        do {
            let html = try NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding)
            print("HTML: \(html)")
        } catch {
            print("x")
        }

    }

}

getData("Google.com")

I need help with later printing out the variable 'html' and any other case printing out the error that forced the catch throw. With the current code it prints out "x". I want to print out why it forced that catch I can know what went wrong and why 'html' did not print.

Cody Weaver
  • 4,756
  • 11
  • 33
  • 51
  • possible duplicate of [Swift do-try-catch syntax](http://stackoverflow.com/questions/30720497/swift-do-try-catch-syntax) – Eric Aya Aug 28 '15 at 12:13
  • @EricD. I am trying to see if there a way to print out what forced that catch statement? I want to know like why didn't my code print out 'html' instead it printed out 'x'. – Cody Weaver Aug 28 '15 at 18:26
  • 1
    Replace `print("x")` with `print(error)`. This `error` variable is not yours, it's generated by the `do catch` mechanism. Try it. :) // Like in [this example](http://stackoverflow.com/a/32187781/2227743). // Next step: create your own error types as explained in the duplicate link. – Eric Aya Aug 28 '15 at 18:30

1 Answers1

0

Create Enum field of ErrorType with error types and iterate through them with do ... catch syntax ... u have already answer on this topic:

Swift do-try-catch syntax

Community
  • 1
  • 1
Kristijan Delivuk
  • 1,253
  • 13
  • 24
  • how do I actually print out the error that happened. – Cody Weaver Aug 28 '15 at 07:14
  • i dont understand your question ? u want to print error where ? – Kristijan Delivuk Aug 28 '15 at 07:35
  • Is there a way to print out what forced that catch statement? I want to know like why didn't my code print out 'html' instead it printed out 'x'. – Cody Weaver Aug 28 '15 at 18:26
  • well as i told u make enum with error types like enum MyErrors : ErrorType { case BadFile case BadNetwork } and then u iterate through errors with do { let sandwich = try doSomeFunction(function) print("i did function") } catch MyErrors.BadFile { print("Bad File") } catch MyErrors.BadNetwork { print("Bad Error") } catch { print("random error") } – Kristijan Delivuk Aug 28 '15 at 18:33
  • look at comment above that was what I was looking for the part print(error) – Cody Weaver Aug 28 '15 at 18:47