I am trying to throw an error when I have status code 500. when I hit this line completion(.failure(error!)) I have "Fatal error: Unexpectedly found nil while unwrapping an Optional value" is they are a problem with my URL session functional?
func PutRoleLedgerTransaction_DebitDistributorBalance(...,completion: @escaping (Result<Data, Error>) -> Void){
let jsonData = role_ledger_object.data(using: .utf8)
let componentURL = createURLComponents(path: "")
print(componentURL.url!)
guard let validURL = componentURL.url else {
print("URL creation failed...")
return
}
var request = URLRequest(url:validURL)
request.setValue("application/json", forHTTPHeaderField: "Content-Type" )
request.setValue("application/json", forHTTPHeaderField: "Accept" )
request.httpMethod = "PUT"
request.httpBody = jsonData
URLSession.shared.dataTask(with: request) { (data, response, error) in
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 > 300{
completion(.failure(error!))
return
}
}
guard let validData = data, error == nil else {
completion(.failure(error!))
return
}
do {
completion(.success(validData))
} catch let serializationError {
completion(.failure(serializationError))
}
}.resume()
}