4

I want to know how you guys handle errors when using a URLRequest in your app. How do you go about notifying your users that an error has occurred? Do you even notify your users at all? Do you try and reload the URLRequest again? Do you tell your users to close the current screen and open it again with an alert box? I have no clue.

Once there's an error, your app stops. So what do you do when this happens and you have a network issue, bad Json data?

What do you do when you get a "Bad Network Connection (The server is down)" or the URLSession comes back with an error and the internet connection is fine?

Please look at the code below and help me figure out what needs to be done when an error occurs.

    let url = URL(string:"http://example/jsonFile.php")
    var request = URLRequest(url:url!)
    request.httpMethod = "POST"
    let postingString = "id=\(id)"

    request.httpBody = postingString.data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request as URLRequest){(data, response, error) -> Void in

        if error != nil {

            print("error \(error)")

            // *****
            // What do you do here? Do you tell your users anything?
            // *****

            return
        }

        // Check for Error
        if let urlContent = data {

            do{
                let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: .allowFragments) as! [String: AnyObject]

                print("jsonResult \(jsonResult)")

            }
            catch{

                print("JSON serialization failed")

                // *****
                // What do you do here? Do you tell your users anything?
                // *****
            }
        }
    }
    task.resume()
user3111472
  • 197
  • 1
  • 11

1 Answers1

1

It is often a bad idea to hide the errors and do nothing (see Error Hiding Anti-Pattern). Unfortunately, handling errors is not easy and can be tedious some times. Pretty code examples quickly become "uglier" when exceptions and errors have to be handled. It takes time to learn to do it well.

In the case of network connections, you would want to wrap your requests into asynchronous methods that take a completion callback as parameter. This callback will often receive a successful result or an error, sometimes wrapped in an enum to remove ambiguity (see Result as an example).

Once you know a network request has failed, you can present that information to the user in a clean, informational but non-obstructive way. To find out what other applications do in this scenario, turn on Airplane Mode in your phone and poke around.

Here are some examples:

Apple Music

Apple Music

Facebook Messenger

enter image description here

Community
  • 1
  • 1
Eneko Alonso
  • 16,651
  • 6
  • 54
  • 76
  • Thanks for your response, but what if I get an URLSession error or the JSON serialization failed. What do I do then? Do I try to reload the URLRequest again myself? Do I make the user close the app and open again? When you get a data error. How do you go about it? I know how to handle an error if there's no internet connection. – user3111472 Feb 10 '17 at 23:31
  • That depends on your business requirements. For example, if a GET request to load a collection from a server fails, it is easy to let the user try again (you can show an alert or an empty state on your table view), having the user press a "Reload" button or pull-to-refresh. If the error however is on a POST/PUT/DELETE request where you are making changes in the server, you should inform the user that the error happened and determine if it is safe to try again. – Eneko Alonso Feb 13 '17 at 05:09
  • 1
    To this, I would add that where possible, you should avoid showing alerts unless there's a good reason for the user to take some action. If it is safe to silently retry (e.g. if you're issuing a truly idempotent GET request that doesn't change server state), you should retry silently. Show something to tell the user that things are wrong so that the user doesn't think your app has failed, but don't require the user to tap an okay button or a retry button, because that extra step provides no benefit for the user (unless the user has been away from the app for a long time). – dgatwood Feb 16 '17 at 19:32