swifthttpresponsensurlsessionfoundationnshttpurlresponse

How to handle 500 http errors


I am trying to access the custom server response body for 500 errors in class HTTPURLResponse (URLResponse) using URLSession.shared.dataTask function. I can only have access to statusCode and allHeaderFields but it doesn't seem to help.

The equivalent in java for ex. is HttpURLConnection.getErrorStream(), but I cannot find something similar in pure swift (I would like to solve this without using 3rd party libs).

How can I get the text response for the 500 error?


Solution

  • let task = session.dataTask(with: urlRequest) { data, response, error in
        if let data = data, let response = response as? HTTPURLResponse {
            switch response.statusCode {
            case 500...599:
                let yourErrorResponseString = String(data: data, encoding: .utf8)
            default:
                break
            }
        }
    }