title: Handling errors in Swift
body: <p>In my application I need to download a JSON file from the web. I have made a <code>ResourceService</code> class that have a <code>download</code> method as seen below. I use this service in "higher level" services of my app. You can see there are multiple of things that may go wrong during the download. The server could be on fire and not be able to successfully respond at the moment, there could be go something wrong during the moving of the temporary file etc.</p>
  
  <p>Now, there is probably not much a user can do with this other than trying later. However, he/she probably want to know that there was something wrong and that the download or the behaviour of the "higher level" methods could not succeed. </p>
  
  <p>Me as a developer is confused as this point because I don't understand how to deal with errors in Swift. I have a <code>completionHandler</code> that takes an error if there was one, but I don't know what kind of error I should pass back to the caller.</p>
  
  <p>Thoughts: </p>
  
  <p>1) If I pass the error objects I get from the NSFileManager API or the NSURLSession API, I would think that I am "leaking" some of the implementation of <code>download</code> method to the callers. And how would the caller know what kind of errors to expect based on the error? It could be both.</p>
  
  <p>2) If I am supposed to catch and wrap those errors that could happen inside the <code>download</code> method, how would that look like? </p>
  
  <p>3) How do I deal with multiple error sources inside a method, and how would the code that calls the method that may throw/return NSError objects look like?</p>
  
  <p>Should you as a caller start intercepting the errors you get back and then write a lot of code that differentiates the messages/action taken based on the error code? I don't get this error handling stuff at all and how it would look like when there are many things that could go wrong in a single method. </p>
  
  <pre><code>func download(destinationUrl: NSURL, completionHandler: ((error: NSError?) -&gt; Void)) {
      let request = NSURLRequest(URL: resourceUrl!)
  
      let task = downloadSession.downloadTaskWithRequest(request) {
          (url: NSURL?, response: NSURLResponse?, error: NSError?) in
  
          if error == nil {
              do {
                  try self.fileManager.moveItemAtURL(url!, toURL: destinationUrl)
              } catch let e {
                  print(e)
              }
          } else {
          }
      }.resume()
  }
  </code></pre>