DEV Community

Discussion on: Declarative Networking with Combine

Collapse
 
muradjamal1981 profile image
Murad Es-heilah • Edited

Thank you for the great article, however, if I change the URL of a request to something like: blahblah.com (or any fake url) this won't let the ApiErrorResponse report the error because there is a missing pipeline operator which is .mapError, the main pipeline would become:

 extension URLSession {
       func dataTaskPublisher<Output: Decodable>(for request: URLRequest) -> AnyPublisher<Output, Error> {
           dataTaskPublisher(for: request)
            .mapError { ApiErrorResponse(message: $0.localizedDescription) }
            .validateStatusCode{ (200..<300).contains($0) }
            .mapJsonError(to: ApiErrorResponse.self, decoder: JSONDecoder())
            .mapJsonValue(to: Output.self, decoder: JSONDecoder())
            .eraseToAnyPublisher()
       }
   }
Enter fullscreen mode Exit fullscreen mode

I've created a mock ApiErrorResponse type as follows:

struct ApiErrorResponse: Error, Decodable {
    var message: String

    enum CodingKeys: String, CodingKey {
        case message = "message"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder .container(keyedBy: CodingKeys.self)
        let message: String = try container.decode(String.self, forKey: .message)
        self.message = message
    }

    init(message: String) {
        self.message = message
    }
}
Enter fullscreen mode Exit fullscreen mode