public func requestData<E,D> (method: HttpMethod, path: ApiPathConstantse, parameters: E?) async throws -> D where E: Encodable, D: Decodable {
let UrlRequest = handelHttpMethod(method: method, path: path, parameter: parameters)
do {
let (data, response) = try await URLSession.shared.data(for: UrlRequest)
guard let response = (response as? HTTPURLResponse) else {
throw RequestError.invalidResponse
}
let statusCodes = response.statusCode
print("\(statusCodes)")
guard (200...299).contains(statusCodes) else {
switch statusCodes {
case 400:
throw RequestError.invalidResponse
case 401:
throw RequestError.authorizationError
case 404:
throw RequestError.notFound
case 500:
throw RequestError.internalError
case 502:
throw RequestError.serverError
case 503:
throw RequestError.serverUnavailable
default:
throw RequestError .invalidResponse
}
}
do {
let result = try JSONDecoder().decode(D.self, from: data)
#if DEBUG
printNetworkProgress(urlRequest: UrlRequest, parameters: parameters, results: result)
#endif
return result
} catch {
throw RequestError.jsonDecodeFailed(error as! DecodingError)
}
}catch {
print(error.localizedDescription)
throw RequestError.unknownError(error)
}
}
requestData 函數是一個泛型函數,它接受四個參數: