Error Handling

Error Handling in Swift 3.0

Error Handling:

Error is an issue or unexpected condition that may cause a program to not function properly. Error can be compile time or runtime.
Error Handling is a process of identifying, catching and recovering  the error conditions.

Here we are trying to handle server side error which occurred while sending request or receiving response. These errors maybe of the following types:

  1. No internet connection
  2. Connection Failed i.e. Request time out, bad url, unsupported url, cannot find host, network connection lost, Resource unavailable.
  3. Security/ Authentication: It may be App authentication or User authentication.
  4. Infrastructure error i.e. Version mismatch, Database connectivity problem
  5. Server App Issue: Server application have any issue to respond the request.
  6. Validation Error: The request is correct but due to some validation response is not expected. These are server’s custom error.

All errors from 1 to 5 returns object of Error protocol. Validation errors are custom errors which are generated by server app. So here we don’t receive any Error Object. Here we need to make our own class object.
To do that make your custom error handling class in which you can handle all of these errors from one class

Required Classes and methods:

To do that we need two classes:

  1. ErrorManager:  In this class we define a method

    processError(error: Error? = nil, errorCode: Int? = nil, errorMsg: String? = nil) -> ErrorModel.
    This method is called where we receive any error in response from http or any validation from our server which is not an object of a error class.

  2. ErrorModel: In ErrorModel class we have two methods, one is for error object other is to make custom error.

Steps to Handle error:

  1. Make class ErrorManager and define a static method processError(error: Error? = nil, errorCode: Int? = nil, errorMsg: String? = nil) -> ErrorModel.


    In this method we have three parameters:

    • error:  Object of Error protocol received from server.
    • errorCode: Custom or your server’s error code.
    • errorMessage: Server’s error description or your custom message.


    You can use this method by passing either Error object or error code and error message i.e.


    OR
  2. There are two methods defined in ErrorModel class, one is for Error Object and other is for custom error. Define variables code, message and title which may used later in your view controller.

    Here you can change message by checking error code.

Leave a Reply