NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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!

1      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.