A server 500 response is necessarily not equal to an URLSession
error, you must not unwrap the optional carelessly.
Create a custom error
enum HTTPResponseError : Error {
case serverFailed(String)
}
In the closure first handle the URLSession
error, then the response and return the message if the status code is not 200
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error { completion(.failure(error)); return }
if let httpResponse = response as? HTTPURLResponse {
print("PutRoleLedgerTransaction API status: (httpResponse.statusCode)")
let message: String = HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode)
print("httpResponse.allHeaderFields (message)")
if httpResponse.statusCode != 200 {
completion(.failure(HTTPResponseError.serverFailed(message)))
return
}
}
// The do block makes no sense if no error is being thrown
// do {
// force unwrapping data is safe if error is nil.
completion(.success(data!))
// } catch {
// completion(.failure(error))
// }
...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…