How to handle 500 http errors

4k Views Asked by At

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?

3

There are 3 best solutions below

1
meggar On BEST ANSWER
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
        }
    }
}
0
dlggr On

There is no way you can get the response data out of HTTPURLResponse. It only contains header information.

If you want to retrieve the response data, you need to use something like dataTask(with:completionHandler:) to send your request. That function passes (Data?, URLResponse?, Error?) to your completion handler. The data parameter of the completion handler is the data returned by the server.

For example:

import Foundation

let url = URL(string: "http://httpstat.us/500")!

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard let data = data, let response = response as? HTTPURLResponse else {
        return
    }

    switch response.statusCode {
    case 500...599:
        print(String(data: data, encoding: .utf8) ?? "No UTF-8 response data")
    default:
        print("not a 500")
    }
}

task.resume()

Edit: Removed force unwrap according to @Rob‘s suggestion

0
Terry Carmen On

There is no way to get more details about a 500 error from the client side.

500 is "Internal Server Error" and it's intentionally vague and unhelpful since disclosing information about the cause of the error would assist hackers in compromising the site.

However you can get a great deal of information about the error from the server log and the log for whatever was processing your code on the server side (php, etc.).

If you have access to the server logs and don't see enough information, you can increase the level of logging for the server and application.