Skip to content

Instantly share code, notes, and snippets.

@ekscrypto
Created February 21, 2019 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekscrypto/9d236158665f105706af19aae79ff1c8 to your computer and use it in GitHub Desktop.
Save ekscrypto/9d236158665f105706af19aae79ff1c8 to your computer and use it in GitHub Desktop.
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