Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Handle Errors

URL requests can sometimes go wrong. Learn how to handle errors during networking operations.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Errors happen all the time, especially when working with networks. There are two levels of errors to think about when working with URL requests: 1. Thrown errors from the functions themselves. 2. Non-successful HTTP status codes.

func downloadSong(at url: URL) async throws {   // THIS IS NEW!
  …
}
class SongDownloader: ObservableObject {
  // MARK: Song Download Error
  enum SongDownloadError: Error {
    case invalidResponse
  }

  …
}
let (downloadURL, response) = try await session.download(from: url)
throw SongDownloadError.invalidResponse
enum SongDownloadError: Error {
  case documentDirectoryError       // THIS IS NEW!
  case invalidResponse
}
guard let documentsPath = fileManager.urls(for: .documentDirectory,
                                           in: .userDomainMask).first
else {
  throw SongDownloadError.documentDirectoryError    // THIS IS NEW!
}
enum SongDownloadError: Error {
  case documentDirectoryError
  case failedToStoreSong        // THIS IS NEW!
  case invalidResponse
}
do {
  if fileManager.fileExists(atPath: destinationURL.path) {
    try fileManager.removeItem(at: destinationURL)
  }
        
  try fileManager.copyItem(at: downloadURL, to: destinationURL)
} catch {
  throw SongDownloadError.failedToStoreSong     // THIS IS NEW!
}
@MainActor @State private var showDownloadFailedAlert: Bool = false
do {
  try await downloader.downloadSong(at: previewURL)
} catch let error {
  print(error)

  showDownloadFailedAlert = true
}
Button(action: {
  Task {
    await downloadTapped()
  }
}) {
  if isDownloading {
    Text("Downloading...")
  } else {
    Text(downloader.downloadLocation == nil ? "Download" : "Listen")
  }
}   
    // THIS IS NEW!!!!
.alert("Download Failed", isPresented: $showDownloadFailedAlert) {
  Button("Dismiss", role: .cancel) {
        showDownloadFailedAlert = false
    }
}
.disabled(isDownloading)

Reviews

Comments