iosswiftviper-architecture

Swift handling error responsibilities using VIPER and services


I have found this article how to build viper module. One thing is still under question for me that I don't know which element is responsible for handling response or whether that handling should be handled in part by 2 or more V, I, P, E, or R elements.

So we have next queue usually in VIPER cycle

  1. ViewController requests presenter to do smth on viewDidLoad for example download smth in background.
  2. Presenter requests Interactor func to do some side work such as call to some services
  3. Services do some NSURLSession request and call back to Interactor.

It's obvious queue as you can see if you familiar to VIPER I skipped some protocols and VIPER element extensions.

In the link above we have a func:

static func getPosts(completionHandler: @escaping ([Post]?, Error?) -> Void) {

as you can see it does not return a raw response on completion but rather do some checks for data and errors.

And my question is this legal? I think there is violation of Single Responsibility or at least VIPER violation.

What is the best place to check errors, is this better to inject some data-builder into service func where a guy gets post.

Or maybe we need to call back with raw response and allow presenter to do all needed checks for errors, data empty and etc. Please does not block this question as this is important to see your comments at least.


Solution

  • One thing is still under question for me that I don't know which element is responsible for handling response.

    1. VIPER only tells about the required parts for a single module. It doesn't force your Interactor to depend directly on Storage/Cache/NetworkClient. You can also have additional entities like Repository so your dependencies would become like Interactor -> Repository -> NetworkClient.
    2. It's totally fine that NetworkClient can pass either data or error. However would be more Swifty to provide Result<[Post], NetworkClientError> in this case.

    In this case it's fine that Interactor handles network-related errors. E.g. Interactor could decide to make a few attempts of retry in case the error is related to internet connection.