Alamofire+Combine: how to get custom error type out of AFError

Viewed 1527

I'm using Alamofire and its Combine helpers to do a simple network request as follows:

class AlamofireClient {
    func getData<T: Decodable>(request: URLRequestConvertible) -> AnyPublisher<T, APIError> {
         AF.request(request)
            .validate()
            .publishDecodable(type: T.self)
            .value()
            .mapError(APIError.init(error:))
            .eraseToAnyPublisher()
    }
}

enum APIError: Error {
    init(error: AFError) {
        self = .network
    }
    
    case network
    case custom(Int, String, String)
    
    var message: String {
        switch self {
        case .network:
            return "Network Error"
        case .custom(let code, let message, let technicalMessage):
            return "Custom error info are: \(code) -- \(message) -- \(technicalMessage)"
        }
    }
}

I'm stuck at extracting the custom error info that is returned from the server, which's in my case has 3 items: code, message and technicalMessage.

1 Answers

So i had worked over similar situation where i wants to pass my own Error, instead of Alamofire. Please see the below code implementation i used, its working for me. Hopefully it will help some one too.

 public func request<T>(response: @escaping (AnyPublisher<T, MyNetworkError>) -> ()) where T : Decodable {
        response(
        MyNetwork.shared.sendRequest(path: “sample/url/endpoints”)
            .validate()
            .publishDecodable(type: T.self)
            .value()
            .mapError{MyNetworkError.networkError(error: ($0 as Error))}
            .eraseToAnyPublisher())
    }

While my own error looks like below.

public enum MyNetworkError: Error {
    case networkError(error: Error)
}
Related