Created
February 21, 2019 01:45
-
-
Save ekscrypto/9d236158665f105706af19aae79ff1c8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension APIRequest { | |
public static func processResponse<T: Codable, E: Codable>( | |
_ dataOrNil: Data?, | |
_ urlResponseOrNil: URLResponse?, | |
_ errorOrNil: Error?, | |
onSuccess: ((_: T) -> Void), | |
onError: ((_: E?, _: Error) -> Void)) { | |
if let data = dataOrNil { | |
do { | |
let decodedResponse = try JSONDecoder().decode(T.self, from: data) | |
onSuccess(decodedResponse) | |
} catch { | |
let originalError = error | |
do { | |
let errorResponse = try JSONDecoder().decode(E.self, from: data) | |
onError(errorResponse, APIError.errorResponseDetected) | |
} catch { | |
onError(nil, originalError) | |
} | |
} | |
} else { | |
onError(nil, errorOrNil ?? APIError.noData) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment