Skip to content

Instantly share code, notes, and snippets.

@jmarkstar
Last active June 6, 2023 16:45
Show Gist options
  • Save jmarkstar/5f7aeda2bc8078ee8837574a20aa00c6 to your computer and use it in GitHub Desktop.
Save jmarkstar/5f7aeda2bc8078ee8837574a20aa00c6 to your computer and use it in GitHub Desktop.
Decode Alamofire response to a Generic codable type but if we get http code 400, I decode different json which is a error message.
@discardableResult
private func performRequest<T:Decodable>(route: APIRouter, decoder: JSONDecoder = JSONDecoder(), completion:@escaping (Int, Result<T>)->Void) -> DataRequest {
return Alamofire.request(route).responseData() { responseData in
guard let response = responseData.response else {
completion(APIClient.responseErrorCode, .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
return
}
print(response)
switch response.statusCode {
case 200...299 : //This case will parse the T type.
guard let data = responseData.data else {
completion(APIClient.parsingJsonErrorCode,
.failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
return
}
do {
let responseCodableObject = try decoder.decode(T.self, from: data)
print("responseCodableObject: \(responseCodableObject)")
completion(response.statusCode, .success(responseCodableObject))
} catch let error {
print("Parsing Error: \(error)")
completion(APIClient.parsingJsonErrorCode,
.failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
}
case 400: //This case will parse the ErrorMessageResponse type
guard let data = responseData.data else {
completion(APIClient.parsingJsonErrorCode, .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
return
}
do {
let errorMessage = try decoder.decode(ErrorMessageResponse.self, from: data)
print("errorMessage: \(errorMessage)")
completion(response.statusCode, .failure(ApiError.internalServerError(errorMessage.mensaje)))
} catch let error {
print("Parsing Error: \(error)")
completion(APIClient.parsingJsonErrorCode,
.failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
}
case 403:
completion(response.statusCode, .failure(ApiError.invalidToken))
default:
completion(APIClient.responseErrorCode,
.failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment