英文:
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) ->URLRequest? {
guard var urlComponents = URLComponents(string:client.baseUrl + client.path) else {
return nil
}
urlComponents.query = "\(client.params)"
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<T:Codable>(client: ServiceClient, type:T.Type) -> AnyPublisher<T,ServiceError> {
dataTask?.cancel()
guard let request = URLRequest.getRequest(client: client) else {
return ServiceError.requestNotCreated(message: Constants.requestNotCreated)**// error is here**
}
}
Here is the screenshot ..
答案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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论