-1

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()
0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

The error is linked to an issue with the URLSession object. The fact that the request was sent successfuly doesn't count as an error.

From the perspective of URLSession:
Request Sent: OK
Response (without checking its content) Received: OK
So error? NO.

What you're thinking is that the server considered your request as an error (missing param, wrong URL etc.), but that's an HTTP Error then, so you read the HTTPURLResponse and maybe some response data sent back where it can gives more info about your issue.

Alamofire and other third party lib might indeed put HTTP Errors into their "Error" management and "combine" with URLSession error.

In the "World Wide Web" (or even local networks), you can customize so much the way your server respond: headers, request types, content returned, etc. There are some convention, but you never know when a server might respond you in a strange way.

URLSession is just "low level" (well, there is lower level) or rather quite "raw" material to work with, so it handles its own error, not the "server ones".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.