Cannot convert return expression of return type ‘AnyPublisher

huangapple go评论59阅读模式
英文:

Cannot convert return expression of return type 'AnyPublisher<T, ServiceError>'

问题

不能将类型为 'ServiceError' 的返回表达式转换为类型 'AnyPublisher<T, ServiceError>'。

英文:

I am new to combine . I have the generic function by using combine and return the Result which is T and Error (service error ). I am trying to pass the custom error message if the URL request is failed . It giving me following errors ..

Cannot convert return expression of type 'ServiceError' to return type 'AnyPublisher<T, ServiceError>'

Here is my URLRequest code ..

import Foundation

extension URLRequest {
    static func getRequest(client: ServiceClient) -&gt;URLRequest? {
        guard var urlComponents = URLComponents(string:client.baseUrl + client.path) else {
            return nil
        }
        urlComponents.query = &quot;\(client.params)&quot;
        guard let url = urlComponents.url else {
            return nil
        }
        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = client.method
        return urlRequest
    }
}

Here is the network layer code ..

class ServiceImpl: Service {

    let urlSesson = URLSession(configuration: .default)
    var dataTask:URLSessionDataTask?

    func fetchData&lt;T:Codable&gt;(client: ServiceClient, type:T.Type) -&gt; AnyPublisher&lt;T,ServiceError&gt; {

        dataTask?.cancel()

        guard let request = URLRequest.getRequest(client: client) else {
            return ServiceError.requestNotCreated(message: Constants.requestNotCreated)**// error is here** 
        }
    }

Here is the screenshot ..

Cannot convert return expression of return type ‘AnyPublisher<T, ServiceError>‘

答案1

得分: 0

返回的方法声明为要返回一个 Publisher,因此你需要返回一个代表错误的发布者。专门用于此目的的发布者是 Fail

return Fail(outputType: type, failure: 
    ServiceError.requestNotCreated(message: Constants.requestNotCreated
).eraseToAnyPublisher()
英文:

The method is declared to return a Publisher, so you need to return a publisher that represents an error. There is just a publisher for exactly that purpose - Fail:

return Fail(outputType: type, failure: 
    ServiceError.requestNotCreated(message: Constants.requestNotCreated
).eraseToAnyPublisher()

huangapple
  • 本文由 发表于 2023年3月9日 20:34:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定