How do you return a Publisher error?

I'm trying to wrap my head around Combine still, and so in my class that handles web requests I've written this method:


static func downloadNumbersPublisher(datesByType: [LottoType: (start: Date, end: Date)]) -> URLSession.DataTaskPublisher {
    guard let url = downloadUrl(using: datesByType) else { return }

    var request = URLRequest(url: url)
    request.addValue("gzip", forHTTPHeaderField: "Accept-Encoding")

    let session = URLSession(configuration: .ephemeral)
    return session.dataTaskPublisher(for: request)
}


What I'm not clear on though is what I actually return on line 2, the guard statement.

Post not yet marked as solved Up vote post of Gargoyle Down vote post of Gargoyle
5.2k views

Replies

what you return on line 2 is in case you fail.


I would try either:

- make the func failable, so it would return nil

- or create an instance of the correct type


Note: I do not find in reference the DataTaskPublisher for URLSession (URLSession.DataTaskPublisher)

I just find

func dataTask(with url: URL) -> URLSessionDataTask

Something like that, should work for your specific need.

func fetchFeeds() -> AnyPublisher<Any, Error> {
    guard let feedsURL = feedsURL else {
        return Fail(error: NSError(domain: "Missing Feed URL", code: -10001, userInfo: nil)).eraseToAnyPublisher()
    }

    ...
}