I am doing a POST request using URLSession.shared.dataTask which returns data, response and error. I would think that Error would be the same as a failed request. However, I can get the request to return proper JSON and httpStatus.statusCode is still 500. Error is nil. Alternatively if the request fails, I can see the html via the data object. However, the statusCode is also returning 500
How can statusCode be 500? The error nil and the request still return JSON or in general the difference between Error and response.statusCode. Given that what is proper way to parse what the dataTask returns. (Someone I asked about this told me the server is not properly configured but I can't verify this and don't have control of it as it is a shared hosting service.)
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response:
URLResponse?, error: Error?) in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
// open 3 //check for http errors
print(httpStatus)//prints 500
}
if let `error` = error {
print(error.localizedDescription)//NO error
return
}
if let `data` = data {
let dataText = String(data: data, encoding: .utf8)
print(dataText)//in event of failure prints out html
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let jsonResults = responseJSON as? [String: Any] {
//In the event of success, parse the JSON here as in
let responsestr = jsonResults["response"] as? [String: Any]
let message = responsestr!["message"] as? String
print(message)
}
task.resume()
I would think that Error would be the same as a failed request.
You need to stop thinking that. Connecting to the server and being handed back a result — any result — is not an Error. An Error is, like, there is no internet, or the host in the address could not be resolved. You are getting a server response in good order. Just to give a clearer example: a 404 response, because the server has rejected the given path, is not an Error.
Typically in these situations the JSON contains a description of what the problem is. Just to repeat my earlier example: in case of a 404, you typically will get good JSON as a response. It just won't be JSON encoding the content of a remote resource: it will be JSON encoding an error message from the server.
Note that part of the problem here is that in your code you are using JSONSerialization.jsonObject
to decode. If you would do this properly, you would have a model object type that is Decodable and you would attempt to decode as that object type. If that fails, you didn't get the data you were hoping for you. But you did get data, namely, an encoded error message.
On the other hand, if you get a 500 response and the model object data type you were expecting, representing the requested resource, then, as you've already been told, that is between you and the server. You need to work it out with whoever runs the server.