BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

Error handling with dataTaskPublisher.

Forums > SwiftUI

Hey guys, I am currently learning about Combine framework and how to use it. I am quite amazed but there are some things that still make me feel dull.

For example. I've got that network call that I am working on.

private func fetchFollowersAppleWay() {

      guard let url = URL(string: endPointString) else { return }

      let decoder = JSONDecoder()
      decoder.keyDecodingStrategy = .convertFromSnakeCase

      var fetchFollowersCancellable = URLSession.shared
         .dataTaskPublisher(for: url)
         .tryMap { element -> Data in
            guard let httpResponse = element.response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
               throw URLError(.badServerResponse)
            }
            return element.data
         }
         .decode(type: [Follower].self, decoder: decoder)
         .sink { error in
            self.fetchingError = error
            // Cannot assign value of type 'Subscribers.Completion<Error>' to type 'Error?'
         } receiveValue: { followers in
            self.followers = followers
         }
   }

My main point right now, is to handle errors as well as possible. With UIKit, I would have handled it like this:

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let _ = error { completed(.failure(.unableToComplete))}

            guard let response = response as? HTTPURLResponse, response.statusCode == 200 else { completed(.failure(.invalidResponse)); return}

            guard let data = data else { completed(.failure(.invalidData)); return}

            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let followers = try decoder.decode([Follower].self, from: data)
                completed(.success(followers))
            } catch { completed(.failure(.invalidData)) }

I am not sure how to handle errors properly with that newer Publisher. Any help appreciated, thanks!

3      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.